// testSVGDlg.cpp : implementation file
//

#include "stdafx.h"
#include "testSVG.h"
#include "testSVGDlg.h"
#include "DialogPathwayGenerator.h"
#include "DialogPathwayGeneratorSetup.h"
#include "DialogMotifsChoices.h"
#include "DialogSourceNodesSetup.h"
#include "DialogUserRegistration.h"
#include "DialogShuffledNetworks.h"
#include "DialogIntermediates.h"

//USE THIS WHEN COMPILING WITH LATER VERSIONS OF VC++
//#include <complex>
#include <fstream>
#include <iostream>

//USE THESE WHEN COMPILING OLDER VERSIONS OF VC++
#include <math.h>
//#include <fstream.h>
#include <atlbase.h>
#include <direct.h>

#include "WinGraphviz.h"
#include "DialogViewer.h"
#include "DialogInteractionsMatrix.h"
#include <afxinet.h>
#include <ctype.h>
#include ".\testsvgdlg.h"

//USE THIS WHEN COMPILING WITH LATER VERSIONS OF VC++
using namespace std;

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

#define NUMBER_OF_ENTRIES_IN_CUES_TO_MOTIFS 100

const IID IID_IDOT = {0xA1080582,0xD33F,0x486E,{0xBD,0x5F,0x58,0x19,0x89,0xA3,0xC7,0xE9}};
						
const CLSID CLSID_DOT = {0x55811839,0x47B0,0x4854,{0x81,0xB5,0x0A,0x00,0x31,0xB8,0xAC,0xEC}};

char DefaultColor[] = "lightblue3";
char DefaultShape[] = "box";
char DefaultVisioShape[] = "Ribosome";

// Data types 
int FindMotifsInRandomNetwork;

int Depth4Search;

//Global variables 
int UseLocalNetworkFlag;
char LocalNetwork[400];

MOLECULE* MoleculesList;
int NumberOfMolecules;

INTERACTION* InteractionsList;
int NumberOfInteractions;

MOLECULE* MatchList;
int NumberOfMatchMolecules;

MOTIF3* Motif3List;
MOTIF4* Motif4List;
int NumberOfMotif3;
int NumberOfMotif4;
MOTIF5* Motif5List;
int NumberOfMotif5;

int DirLevel;

char LastViewerCall[300];

COLORS_AND_SHAPES* ColorsAndShapesList;

VISIO_SHAPE* VisioShapesList;

int MembraneCount;
int CytoCount;
int NucleusCount;
int ERCount; 
int RiboCount; 
int MitoCount; 
int SkeletonCount;
int ExtracellularCount;
int VesicleCount;
char XLocation[200];
char YLocation[200];
double XLocationNumber;
double YLocationNumber;
int ProgressCount;
int ProgressCount2;
int ProgressCount3;
int DoDownstreamMaps;

int IndexOfGlobalList;
int GlobalList[5000];

int A[5000][5000];
char GlobalSource[100];
char GlobalTarget[100];
int GlobalSteps;

int MachinesArray[10];

CWinThread* pThreadCreateWebSite;
CWinThread* pThreadFindMotifs;
CWinThread* pThreadBasedOnConnectivity;
CWinThread* pThreadFromSourceNodes;
CWinThread* pThreadShuffleNetwork;
CWinThread* pThreadProcessList;

char MotifsMessage[400];
char BasedOnConnectivityMessage[400];
char FromSourceNodesMessage[400];
char GeneListMessage[400];

int CountOfEffects;
char* EffectNames[5000];
int EffectCounts[5000];

int CountOfMoleculeTypes;
char* MoleculeTypesNames[5000];
int MoleculeTypesCounts[5000];

int CountOfLocations;
char* LocationsNames[5000];
int LocationsCounts[5000];

int CountOfTypeOfInteractions;
char* TypeOfInteractionsNames[5000];
int TypeOfInteractionsCounts[5000];

int ConnectivityDistributionArray[100];
int InConnectivityDistributionArray[100];
int OutConnectivityDistributionArray[100];

int UndirectedCycles[100];
int DirectedCycles[100];
int ConvergedCycles[100];
int UniqueUndirectedCycles[100];
int UniqueDirectedCycles[100];
int UniqueList[5000];
int UniqueListCount;

int PositiveFeedbackLoops[1000];
int NegativeFeedbackLoops[1000];
int PositiveConvergedCycles[1000];
int Gates[1000];
int ScaffoldCycles[100];
int BifanCycles[100];

int ArrayOfConnectivity[1000];
int ArrayOfConnectors[1000];

int CountOfRandomConnections;

int RandomSources[5000];
int RandomTargets[5000];

ofstream LoopsFile;
MOLECULE* ListToDraw;

char Names1[500][30];
char Names2[500][30];
char Names3[500][30];
char Names4[500][30];
char Names5[500][30];
int Total3Names;
int Total4Names;
int Total5Names;

char szBuff[4097];
bool dispMatrix[1000][1000];

int MotifsBetweenCuesAndTranscription[NUMBER_OF_ENTRIES_IN_CUES_TO_MOTIFS][14];
int MotifsBetweenCuesAndTranslation[NUMBER_OF_ENTRIES_IN_CUES_TO_MOTIFS][14];
int MotifsBetweenCuesAndVesicles[NUMBER_OF_ENTRIES_IN_CUES_TO_MOTIFS][14];
int MotifsBetweenCuesAndMotility[NUMBER_OF_ENTRIES_IN_CUES_TO_MOTIFS][14];
int MotifsBetweenCuesAndChannels[NUMBER_OF_ENTRIES_IN_CUES_TO_MOTIFS][14];

PATHWAY_GENERATOR_SETUP PathwayGeneratorSetupStruct;
int FailedToGeneratePathway;
MOTIFS_CHOICES MotifsChoices;
FROM_SOURCES_CHOICES FromSourceChoices;
int WebSiteFinishedFlag;
char OriginalNetworkName[500];


int ShuffleTypeOfNetwork;
int ShuffleNumberOfNetworks;
bool ShuffleIsIsland;
bool ShuffleCccpl;
bool ShuffleMotif34;
bool ShuffleMotif5;
bool CancelShuffle=false;

int pubMedIds[100000];


MOLECULE* GetNodeBasedOnNumber(int i);


UINT CreateWebSiteThread(LPVOID pParam);
UINT FindMotifsThread(LPVOID pParam);
UINT CreateAllPathwaysThread(LPVOID pParam);
UINT BasedOnConnectivityThread(LPVOID pParam);
UINT FromSourceNodesThread(LPVOID pParam);
UINT ShuffleNetworkThread(LPVOID pParam);
UINT ProcessListThread(LPVOID pParam);

void DumpStringToSVG(CString graphString, char* fileName, int addNavigation, int downstream);
void DumpStringToGIF(CString graphString, char* fileName);
void DumpStringToJPEG(CString graphString, char* fileName);

MOLECULE* AddToMoleculesWithLink(char* name, char* accHuman, char* accMouse, char* type, char* location, int link);
INTERACTION* AddToInteractions(char* source, char* sourceAccHuman, char* sourceAccMouse, char* sourceLocation, char* sourceType, char* target, char* targetAccHuman, char* targetAccMouse,
							   char* targetLocation, char* targetType, char* effect, char* typeOfInteraction, int pmid);
int GetNumberBasedOnString(char* name);
int GetNumberBasedOnStringFromListToDraw(char* name);
void MakeSVGFile(char* name);
void MakeGifFile(char* name);
void MakeBigSVGMap(void);
void MakeHTMLFile(char* name);
void MakePrintableHTMLFile(char* name);
CString AddNavigationBars(CString svgFileWithoutNavigation, int downstream);
char* GetShape(char* name);
char* GetColor(char* name);
int LoadColorsAndShapes(void);
void MakeDownstreamSVGFile(char* name);
void MakeDownstreamHTMLFile(char* name);
CString AddThisInteraction(INTERACTION* tempInteractionNode, CString inputString);
MOLECULE* AddToEndOfListOfNodesToExpand(char* name, MOLECULE* listOfNodesToExpand);
bool NotAlreadyInListToExpand(char* name, MOLECULE* listOfNodesToExpand);
void FreeListOfNodesToExpand(MOLECULE* listOfNodesToExpand);
void CreateStatisticalAnalysisWebPage(void);
void CreateMainWebPage(void);
double ComputeAvgPathLength(void);
double ComputeAvgLinksPerComponent(void);
double ComputeCC(void);
MOLECULE* GetNodeBasedOnNumber(int i);
MOLECULE* GetNodeBasedOnName(char* name);
void CreateIndexPage(void);
MOLECULE* RemoveFromList(MOLECULE* tempNode1);
MOLECULE* AddToNewList(MOLECULE*  newList, MOLECULE* tempNode1);
void SortMoleculeList (void);
void SortMoleculeListBasedOnMotifs(void);
void SortMoleculeListBasedOnConnectivity(void);
void SortMoleculeListBasedOnMachines(void);
void CreateColorsAndShape(void);
void CountNumberOfEffects(void);
void CountNumberOfMoleculeTypes(void);
void CountNumberOfLocations(void);
void CountNumberOfTypeOfInteractions(void);
void SetConnectivityDistribution(void);
double ComputeAvgDownstream(void);
void DumpStringToPS(CString graphString, char* fileName, int addNavigation, int downstream);
void DumpToDot(CString graphString, char* fileName);
void Expand (MOLECULE* sourceNode, MOLECULE* tempNode, int sizeWeLookFor, int howDeep, int* listSoFar);
void CountUndirectedCycles(void);
int NotAlreadyInList(int* listSoFar, int howDeep, int number);
int DirectionOK(MOLECULE* sourceNode, MOLECULE* targetNode);
void ExpandDirectOnly (MOLECULE* sourceNode, MOLECULE* tempNode, int sizeWeLookFor, int howDeep, int* listSoFar);
void ExpandScaffoldOnly (MOLECULE* sourceNode, MOLECULE* tempNode, int sizeWeLookFor, int howDeep, int* listSoFar);
void ExpandBifanOnly (MOLECULE* sourceNode, MOLECULE* tempNode, int sizeWeLookFor, int howDeep, int* listSoFar, int flipFlag);
void CountDirectedCycles(int size, LPVOID pParam);
void CountConvergedCycles(int size, LPVOID pParam);
void MakeTextForVisio(void);
char* GetVisioShape(char* moleculeType);
void LoadVisioShapes(void);
void GetXLocation(char* location);
void GetYLocation(char* location);
void GetColorAndShape(int moleculeTypeIndex, char* colorAndShape);
int GetMoleculeTypeIndex(char* moleculeType);
void ComputeBestLocationsForVisio(void);
void SwapBestXandY(MOLECULE* origNode, MOLECULE* newNode);
double ComputeIfSwappedTotalDistance(MOLECULE* origNode, MOLECULE* newNode);
double ComputeDistanceToNeighbors(MOLECULE* node);
void MakeDownstreamNetFile(char* name);
bool TempNodeAlsoInListToExpand(MOLECULE* listOfNodesToExpand, MOLECULE* tempNode);
void ExpandDirectedUnique(MOLECULE* sourceNode, MOLECULE* tempNode, int sizeWeLookFor, int howDeep, int* listSoFar);
void ExpandUndirectedUnique(MOLECULE* sourceNode, MOLECULE* tempNode, int sizeWeLookFor, int howDeep, int* listSoFar);
void ExpandConvergedOnly (MOLECULE* sourceNode, MOLECULE* tempNode, int sizeWeLookFor, int howDeep, int* listSoFar, int directionFlag);
void CountUndirectedUniqueCycles(void);
void CountDirectedUniqueCycles(void);
void AddToUniqueList(MOLECULE* tempNode, int* listSoFar, int size);
void ShuffleMoleculesList(void);
void ResetUniqueList(void);
void ResetUndirectedUniqueCycles(void);
void ResetDirectedUniqueCycles(void);
bool NotAlreadyInUniqueList(int number);
void InitArrayOfConnectors(void);
void InitArrayOfConnectivity(void);
int GetRandomNumber(int range);
void TakeOutTheHubs(void);
int CheckIfArrayOfConnectivityIsEmpty(void);
int NotAlreadyDumpedRandomConnection(int randomTarget, int randomComponent);
void FreeMoleculesList(void);
void FreeInteractionsList(void);
void FreeReferencesList(void);
int IsItNegativeLoop(int* listSoFar, int size);
int ThereIsNoLinkAlready(INTERACTION* interaction1, INTERACTION* interaction2);
int ExpandIsland(MOLECULE* tempNode, int* listSoFar, int listSoFarIndex);
int CountIslands(void);
void CountInAndOutLinks(void);
int GetLevelBaseOnLocation(char* location);
INTERACTION* GetInteraction(char* source, char* target);
int ExpandSimAfterGlu (MOLECULE* tempNode, int depth, int count);
int ExpandSim (MOLECULE* tempNode, int depth, int count);
void SimulateBothGlutamateAndNE(void);
void SimulateNE(void);
void SimulateGlutamate(void);
void ClearGlutamateVisitedFlagForAllMolecules(void);
void ClearVisitedFlagForAllMolecules(void);
void SimulateGABA(void);
void SimulateAch(void);
void SimulatePQ_Type_Ca(void);
void SimulateAllLigands(void);
void SimulateAllTFs(void);
int ExpandNucleusSearch (MOLECULE* tempNode, int depth, int count);
void SimulateFasL(void);
void LoadMachines(void);
void LoadAccessions(void);
void SimulateAllAtOnce(void);
bool IsNodeInListToDraw(MOLECULE* node);
void AddToListToDraw(MOLECULE* tempNode);
void FreeListToDraw(void);
void SimulateCREB(void);
int ExpandReverseSim (MOLECULE* tempNode, int depth, int count);
int CountNumberOfPathwaysToOutput (MOLECULE* source, int pathwaysCount, int &negatives, int &positives);
int IsNegative(MOLECULE* sourceNode, MOLECULE* targetNode);
void CountNumberOfPathwaysToOutput(char* targetName, MOLECULE* tempNode, int sizeWeLookFor, int howDeep, int* listSoFar, int &positives, int &negatives);
int IsItNegativePathway(int* listSoFar, int size);
void CountNumberOfPathwaysToOutputAndDump(ofstream &out1, char* targetName, MOLECULE* tempNode, int sizeWeLookFor, int howDeep, int* listSoFar, int &positives, int &negatives);
void ClearInteractionsFlag(void);
void AddToGlobalListOfSubNetwork(int* listSoFar, int howDeep);
void AddInteractionsForFeedbackLoops(ofstream &out1);
int LoadNetwork(char* fileName);
void FreeNetwork(void);
void DumpAllVisited(char* fileName);
void MakeSVGMapBasedOnVisited(char* fileName);
int CountAllVisited(void);
void ComputeXYZ(int area, double &x, double &y, double &z);
void DumpNetwork(char* fileName);
MOTIF3* AddMotif3(char* name1, char* name2, char* name3);
MOTIF4* AddMotif4(char* name1, char* name2, char* name3, char* name4);
MOTIF5* AddMotif5(char* name1, char* name2, char* name3, char* name4, char* name5);
void SortMotif3List(void);
void SortMotif4List(void);
void SortMotif5List(void);
void DumpMotif3List(void);
void DumpMotif4List(void);
void DumpMotif5List(void);
MOTIF4* AddToNewMotif4List(MOTIF4*  newList, MOTIF4* tempNode1);
MOTIF3* AddToNewMotif3List(MOTIF3*  newList, MOTIF3* tempNode1);
MOTIF3* RemoveFromMotif3List(MOTIF3* tempNode1);
MOTIF4* RemoveFromMotif4List(MOTIF4* tempNode1);
void FreeMotifs(void);
void SimulateLigandPairs(char* name1, char* name2);
int CountMotif31();
int CountMotif32();
int CountMotif33();
int CountMotif34();
int CountMotif35();
int CountMotif36();
int CountMotif41();
int CountMotif42();
int CountMotif43();
int CountMotif44();
int CountMotif45();
int CountMotif46();
int CountMotif47();
int CountMotif51();
int CountMotif53();
void DumpVisitedMotif3List(char* fileName);
void MarkAllNodesToOutput(char* targetName, MOLECULE* tempNode, int sizeWeLookFor, int howDeep, int* listSoFar);
void MarkInteractionsInBetween(void);
void CheckSameNameSourceTarget(ofstream &validation);
void CheckSameNameDiferentACC(ofstream &validation);
void CheckSameACCDifferentName(ofstream &validation);
void CheckNonMammalianACC(ofstream &validation);
void ListAllTypes(ofstream &validation);
void CheckSameNameDifferentType(ofstream &validation);
void CheckSameNameDifferentLocation(ofstream &validation);
void CheckSamePairDifferentEffectOrInteraction(ofstream &validation);
void CheckSamePairDifferentOrder(ofstream &validation);
void CheckIfExpressedInNeurons(ofstream &validation);
int GetNumberOfReferences(void);
void MakeMachinesSVGMap(char* fileName);
BOOL WriteDIB( LPTSTR szFile, HANDLE hDIB);
BOOL WriteWindowToDIB( LPTSTR szFile, CDC *pDC );
HBITMAP DIBToDDB( HANDLE hDIB );
HANDLE DDBToDIB( CBitmap& bitmap, DWORD dwCompression, CPalette* pPal );
MOTIF5* AddToNewMotif5List(MOTIF5*  newList, MOTIF5* tempNode1);
MOTIF5* RemoveFromMotif5List(MOTIF5* tempNode1);
void DumpToJpegTopMotif3(char* fileName);
void DumpToJpegTopMotif4(char* fileName);
void DumpToJpegTopMotif5(void);
void DumpFlaggedInteractionsToPajek(char* pajekFileName);
void SimulateArp23AndAMPAR(void);
int These3NamesAlreadyBeenHere(char* name1, char* name2, char* name3);
int These4NamesAlreadyBeenHere(char* name1, char* name2, char* name3, char* name4);
int These5NamesAlreadyBeenHere(char* name1, char* name2, char* name3, char* name4, char* name5);
int AreThereInBetweenThese4Connections(char* name1, char* name2, char* name3, char* name4);
int AreThereInBetweenThese5Connections(char* name1, char* name2, char* name3, char* name4, char* name5);
int DownLoadAbstractInTextForPubMedID(int pubMedId);
void GetAuthorARBFormat(int pubMedId, CString& authors);
void GetTitleARBFormat(int pubMedId, CString& title);
void GetYearARBFormat(int pubMedId, CString& year);
void GetJournalARBFormat(int pubMedId, CString& journal);
void GetVolumeARBFormat(int pubMedId, CString& volume);
void GetPagesARBFormat(int pubMedId, CString& pages);
void GetAuthorScienceFormat(int pubMedId, CString& authors);
void GetTitleScienceFormat(int pubMedId, CString& title);
void GetYearScienceFormat(int pubMedId, CString& year);
void GetJournalScienceFormat(int pubMedId, CString& journal);
void GetVolumeScienceFormat(int pubMedId, CString& volume);
void GetPagesScienceFormat(int pubMedId, CString& pages);
double ComputeGC(void);
int LoadTwoColumnNetwork(char* fileName);
int CountAllInteractionsFlags(void);
void CreatePathwaysWebpages(int numberOfMapNames, char* mapNames[]);
int CheckSourceCondition(MOLECULE* tempNode);
int CheckTargetCondition(MOLECULE* tempNode);
void CreatePathwayGeneratorForm(int numberOfMapNames, char* mapNames[]);
void AddToFBL3Array(char* name1, char* name2, char* name3);
void AddToFBL4Array(char* name1, char* name2, char* name3, char* name4);
void AddToPFBL3Array(char* name1, char* name2, char* name3);
void AddToPFBL4Array(char* name1, char* name2, char* name3, char* name4);
void AddToNFBL3Array(char* name1, char* name2, char* name3);
void AddToNFBL4Array(char* name1, char* name2, char* name3, char* name4);
void AddToFFL3Array(char* name1, char* name2, char* name3);
void AddToFFL4Array(char* name1, char* name2, char* name3, char* name4);
void AddToPFFL3Array(char* name1, char* name2, char* name3);
void AddToPFFL4Array(char* name1, char* name2, char* name3, char* name4);
void AddToNFFL3Array(char* name1, char* name2, char* name3);
void AddToNFFL4Array(char* name1, char* name2, char* name3, char* name4);
void AddToSCAFFOLDArray(char* name1, char* name2, char* name3);
void AddToBIFANArray(char* name1, char* name2, char* name3, char* name4);
MOTIF3* AddMotif3(char* name1, char* name2, char* name3, int type, int sign);
MOTIF4* AddMotif4(char* name1, char* name2, char* name3, char* name4, int type, int sign);
MOTIF5* AddMotif5(char* name1, char* name2, char* name3, char* name4, char* name5);
int ScaffoldOK(MOLECULE* sourceNode, MOLECULE* targetNode);
int OppositeDirectionOK(MOLECULE* sourceNode, MOLECULE* targetNode);
int IsNegative(MOLECULE* sourceNode, MOLECULE* targetNode);
int IsItGate(int* listSoFar, int size);
int IsItSymmetric(int* listSoFar, int size);
void CreateWebPageToDisplayTheMotifs4(char* fileName);
void CreateWebPageToDisplayTheMotifs3(char* fileName);
void GetIndexesFor4NodeMotifs(char* name1, char* name2, char* name3, char* name4,
							  int& indexForTranscription,
							  int& indexForTranslation,
							  int& indexForVesicles,
							  int& indexForMotility,
							  int& indexForChannels);
void GetIndexesFor3NodeMotifs(char* name1, char* name2, char* name3, 
							  int& indexForTranscription,
							  int& indexForTranslation,
							  int& indexForVesicles,
							  int& indexForMotility,
							  int& indexForChannels);
char* GetEffectBasedOnNames(char* name1, char* name2);
int GetDirectionBasedOnNames(char* name1, char* name2);
char* GetTypeOfInteractionBasedOnNames(char* name1, char* name2);
int TheSame3TypesEffectsAndDirection(MOTIF3* tempNode, 
				char* type1, char* type2, char* type3,
				char* effect1, char* effect2, char* effect3, 
				int& direction1, int& direction2, int& direction3);
int TheSame4TypesEffectsAndDirection(MOTIF4* tempNode, 
				char* type1, char* type2, char* type3, char* type4,
				char* effect1, char* effect2, char* effect3, char* effect4,
				int& direction1, int& direction2, int& direction3, int& direction4);
int TheSame5TypesEffectsAndDirection(MOTIF5* tempNode, 
				char* type1, char* type2, char* type3, char* type4, char* type5,
				char* effect1, char* effect2, char* effect3, char* effect4, char* effect5,
				int& direction1, int& direction2, int& direction3, int& direction4, int& direction5);
void RotateRight3(char* type1, char* type2, char* type3, char* effect1, char* effect2, char* effect3, 
				int &direction1, int &direction2, int &direction3);

void FlipToInverse3(char* type1, char* type2, char* type3, char* effect1, char* effect2, char* effect3, 
				int &direction1, int &direction2, int &direction3);

void RotateRight4(char* type1, char* type2, char* type3, char* type4, 
				  char* effect1, char* effect2, char* effect3, char* effect4,
				  int &direction1, int &direction2, int &direction3, int &direction4);

void FlipToInverse4(char* type1, char* type2, char* type3, char* type4, char* type5,
					char* effect1, char* effect2, char* effect3, char* effect4, char* effect5,
					int &direction1, int &direction2, int &direction3, int &direction4, int &direction5);
void RotateRight4(char* type1, char* type2, char* type3, char* type4, char* type5,
				  char* effect1, char* effect2, char* effect3, char* effect4, char* effect5,
				  int &direction1, int &direction2, int &direction3, int &direction4, int &direction5);

void FlipToInverse4(char* type1, char* type2, char* type3, char* type4, char* type5,
					char* effect1, char* effect2, char* effect3, char* effect4, char* effect5,
					int &direction1, int &direction2, int &direction3, int &direction4, int &direction5);

int TheSame4Names(MOTIF4* tempNode, 
				char* name1, char* name2, char* name3, char* name4,
				char* type1, char* type2, char* type3, char* type4,
				char* effect1, char* effect2, char* effect3, char* effect4,
				int& direction1, int& direction2, int& direction3, int& direction4);

int DirectionOnlyOK(MOLECULE* sourceNode, MOLECULE* targetNode);
void DeletePubMedIdFile(int pubMedId);
void CreateReducedNetworks(LPVOID pParam);
void ComputeStatsForReducedNetworks(LPVOID pParam);
int CountNeutrals();
int CountNegatives();
int CountPositives();
int CountScaffolds();
int CountBifans();
int CountFeedforwardLoops(int size);
int CountNegativeFeedforwardLoops(int size);
int CountPositiveFeedforwardLoops(int size);
int CountFeedbackLoops(int size);
int CountNegativeFeedbackLoops(int size);
int CountPositiveFeedbackLoops(int size);
void StartViewer(char* fileName);
void CreateSubetworksFromSourceNodes(LPVOID pParam);
int OppositeDirectionOKWithNeutralLinks(MOLECULE* sourceNode, MOLECULE* targetNode);
void ComputeStatsForSubnetworksFromSourceNodes(LPVOID pParam);
int TryToDownloadLicence(CString tempEmail);
void SortAndDumpMotifDensity(ofstream &out1);
bool IsConnected(MOLECULE *mol1, MOLECULE *mol2);
void SortMoleculeListBasedOnReverseConnectivity (void);

void GenerateMiloStyleShuffledNetworks(int n, bool island, LPVOID pParam);
void SwapLinkEffects(int n, LPVOID pParam);
void GenerateErdosRenyiNetworks(int n, bool island, LPVOID pParam);
void FreeNewInteractionsList(INTERACTION* start);
int TryToDownloadSigFile(void);
int TryToDownloadHelpFile(void);
int TryToDownloadHumanInteractionsFile(LPVOID pParam);
int LoadList(char* fileName);
MOLECULE* AddToMatchList(char* name);
void MarkNodes(void);
void FreeMatchList(void);
void Search4Paths(int depth, LPVOID pParam);
void CountNumberOfPathwaysToOutputAndDump(
	ofstream &out, char* targetName, MOLECULE* tempNode, 
	int sizeWeLookFor, int howDeep, int* listSoFar);
int sumFact(int n);
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CTestSVGDlg dialog

CTestSVGDlg::CTestSVGDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CTestSVGDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CTestSVGDlg)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CTestSVGDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CTestSVGDlg)
		// NOTE: the ClassWizard will add DDX and DDV calls here
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CTestSVGDlg, CDialog)
	//{{AFX_MSG_MAP(CTestSVGDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTTON_LOAD_NETWORK, OnButtonLoadNetwork)
	ON_BN_CLICKED(IDC_BUTTON_CREATE_WEB_SITE, OnButtonCreateWebSite)
	ON_BN_CLICKED(IDC_BUTTON_VIEWER, OnButtonViewer)
	ON_BN_CLICKED(IDC_BUTTON_SAVE_AS, OnButtonSaveAs)
	ON_BN_CLICKED(IDC_BUTTON_VALIDATE, OnBnClickedButtonValidate)
	ON_BN_CLICKED(IDC_BUTTON_LOAD_TWO_COLUMN, OnButtonLoadTwoColumn)
	ON_BN_CLICKED(IDC_BUTTON3, OnBnClickedButtonBasedOnConnectivity)
	ON_BN_CLICKED(IDC_BUTTON4, OnBnClickedButtonFromSourceNodes)
	ON_BN_CLICKED(IDC_BUTTON_NET, OnButtonNet)
	ON_BN_CLICKED(IDC_BUTTON_SIF, OnBnClickedButtonSif)
	ON_BN_CLICKED(IDC_BUTTON_GENE_LIST, OnBnClickedButtonGeneList)
	ON_BN_CLICKED(IDC_BUTTON_GENE_LIST_HELP, OnBnClickedButtonGeneListHelp)
	ON_BN_CLICKED(IDC_BUTTON_TWO_COLUMN_HELP, OnBnClickedButtonTwoColumnHelp)
	ON_BN_CLICKED(IDC_BUTTON_RANDOM_HELP, OnBnClickedButtonRandomHelp)
	ON_BN_CLICKED(IDC_BUTTON_MFINDER_HELP, OnBnClickedButtonMfinderHelp)
	ON_BN_CLICKED(IDC_BUTTON_MOTIFS_INPUT, OnButtonMotifsInput)
	ON_BN_CLICKED(IDC_BUTTON_VALIDATE_HELP, OnBnClickedButtonValidateHelp)
	ON_BN_CLICKED(IDC_BUTTON6, OnButtonIslands)
	ON_BN_CLICKED(IDC_BUTTON_SAVE_AS_HELP, OnBnClickedButtonSaveAsHelp)
	ON_BN_CLICKED(IDC_BUTTON_DUMP_CLUSTER_HELP, OnBnClickedButtonDumpClusterHelp)
	ON_BN_CLICKED(IDC_BUTTON_SIF_HELP2, OnBnClickedButtonSifHelp2)
	ON_BN_CLICKED(IDC_BUTTON_SIF_HELP, OnBnClickedButtonSifHelp)
	ON_BN_CLICKED(IDC_BUTTON_PAJEK_HELP, OnBnClickedButtonPajekHelp)
	ON_BN_CLICKED(IDC_BUTTON_GRAPHVIZ_HELP, OnBnClickedButtonGraphvizHelp)
	ON_BN_CLICKED(IDC_BUTTON_PG_HELP, OnBnClickedButtonPgHelp)
	ON_BN_CLICKED(IDC_BUTTON_MATRIX_HELP, OnBnClickedButtonMatrixHelp)
	ON_BN_CLICKED(IDC_BUTTON_MOTIFS_HELP, OnBnClickedButtonMotifsHelp)
	ON_BN_CLICKED(IDC_BUTTON_SUBNET1_HELP, OnBnClickedButtonSubnet1Help)
	ON_BN_CLICKED(IDC_BUTTON_SUBNETS2_HELP, OnBnClickedButtonSubnets2Help)
	ON_BN_CLICKED(IDC_BUTTON_DISTANCE_TO_MACHINES, OnButtonDistanceToMachines)
	ON_BN_CLICKED(IDC_BUTTON_RANDOM_ISLANDS_NETS, OnButtonRandomIslandsNets)
	//}}AFX_MSG_MAP

	ON_MESSAGE(WM_UPDATEWEBSITEPROGRESS, OnUpdateWebSiteProgress)
	ON_MESSAGE(WM_THREADWEBSITEFINISHED, OnThreadWebSiteFinished)
	ON_MESSAGE(WM_UPDATEALLPATHWAYSPROGRESS, OnUpdateAllPathwaysProgress)
	ON_MESSAGE(WM_THREADALLPATHWAYSFINISHED, OnThreadAllPathwaysFinished)
	ON_BN_CLICKED(IDC_BUTTON_DIFF_MAPS, OnBnClickedButtonDiffMaps)
	ON_BN_CLICKED(IDC_BUTTON7, OnButtonRemoveSelective)
	ON_BN_CLICKED(IDC_BUTTON_DUMP_MACHINES_AND_ACCESSIONS, OnBnClickedButtonDumpMachinesAndAccessions)
	ON_BN_CLICKED(IDC_BUTTON_PROGRESS_REPORT, OnBnClickedButtonProgressReport)
	ON_BN_CLICKED(IDC_BUTTON14, OnBnClickedButton14)
	ON_BN_CLICKED(IDC_BUTTON15, OnBnClickedButton15)
	ON_BN_CLICKED(IDC_BUTTON_INDEX_INTERACTIONS, OnBnClickedButtonIndexInteractions)
	ON_STN_CLICKED(IDC_STATIC_PROGRESS, OnStnClickedStaticProgress)
	ON_BN_CLICKED(IDC_BUTTON17, OnBnClickedButton17)
	ON_BN_CLICKED(IDC_BUTTON18, OnBnClickedButton18)
	ON_BN_CLICKED(IDC_BUTTON19, OnBnClickedButton19)
	ON_BN_CLICKED(IDC_BUTTON20, OnBnClickedButton20)
	ON_BN_CLICKED(IDC_BUTTON21, OnBnClickedButton21)
	ON_BN_CLICKED(IDC_BUTTON22, OnBnClickedButton22)
	ON_BN_CLICKED(IDC_BUTTON23, OnBnClickedButton23)
	ON_BN_CLICKED(IDC_BUTTON24, OnBnClickedButton24)
	ON_BN_CLICKED(IDC_BUTTON25, OnBnClickedButton25)
	ON_BN_CLICKED(IDC_BUTTON26, OnBnClickedButton26)
	ON_BN_CLICKED(IDC_BUTTON27, OnBnClickedButton27)
	ON_BN_CLICKED(IDC_BUTTON28, OnBnClickedButton28)
	ON_BN_CLICKED(IDC_BUTTON29, OnBnClickedButton29)
	ON_BN_CLICKED(IDC_BUTTON_CREATE_AND_DRAW_PATHWAYS, OnBnClickedButtonCreateAndDrawPathways)
	ON_BN_CLICKED(IDC_BUTTON_SHUFFLED_NETWORKS, OnBnClickedButtonShuffledNetworks)
	ON_BN_CLICKED(IDC_BUTTON30, OnBnClickedButton30)
	ON_BN_CLICKED(IDC_BUTTON_GENERATE_PATHWAY, OnBnClickedButtonGeneratePathway)
	ON_BN_CLICKED(IDOK, OnBnClickedOk)
	ON_BN_CLICKED(IDC_BUTTON_MOTIFS, OnBnClickedButtonMotifs)
	ON_MESSAGE(WM_UPDATE_MOTIFS_SEARCH_PROGRESS, OnUpdateMotifsSearchProgress)
	ON_MESSAGE(WM_THREAD_MOTIFS_SEARCH_FINISHED, OnThreadMotifsSearchFinished)
	ON_MESSAGE(WM_UPDATE_BASED_ON_CONNECTIVITY_PROGRESS, OnUpdateBasedOnConnectivityProgress)
	ON_MESSAGE(WM_THREAD_BASED_ON_CONNECTIVITY_FINISHED, OnThreadBasedOnConnectivityFinished)
	ON_MESSAGE(WM_UPDATE_FROM_SOURCE_NODES_PROGRESS, OnUpdateFromSourceNodesProgress)
	ON_MESSAGE(WM_THREAD_FROM_SOURCE_NODES_FINISHED, OnThreadFromSourceNodesFinished)
	ON_BN_CLICKED(IDC_BUTTON5, OnBnClickedButton5)
	ON_BN_CLICKED(IDC_BUTTON_INTERACTION_MATRIX, OnBnClickedButtonInteractionMatrix)
	ON_MESSAGE(WM_UPDATE_SHUFFLED_PROGRESS, OnUpdateShuffledProgress)
	ON_MESSAGE(WM_THREAD_SHUFFLED_FINISHED, OnThreadShuffledFinished)
	ON_MESSAGE(WM_THREAD_PROCESS_LIST_PROGRESS, OnUpdateProcessListProgress)
	ON_MESSAGE(WM_THREAD_PROCESS_LIST_FINISHED, OnThreadProcessListFinished)
	ON_BN_CLICKED(IDC_BUTTON_CREATE_WEB_SITE2, OnBnClickedButtonCreateWebSite2)
	ON_BN_CLICKED(IDC_BUTTON_GENE_LIST_HELP, OnBnClickedButtonGeneListHelp)
	ON_BN_CLICKED(IDC_BUTTON_MOTIFS_INPUT, OnBnClickedButtonMotifsInput)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CTestSVGDlg message handlers

//BOOL CTestSVGDlg::OnInitDialog()
//{
//	CDialog::OnInitDialog();
//
//	int ret;
//	// Add "About..." menu item to system menu.
//
//	// IDM_ABOUTBOX must be in the system command range.
//	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
//	ASSERT(IDM_ABOUTBOX < 0xF000);
//
//	CMenu* pSysMenu = GetSystemMenu(FALSE);
//	if (pSysMenu != NULL)
//	{
//		CString strAboutMenu;
//		strAboutMenu.LoadString(IDS_ABOUTBOX);
//		if (!strAboutMenu.IsEmpty())
//		{
//			pSysMenu->AppendMenu(MF_SEPARATOR);
//			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
//		}
//	}
//
//	// Set the icon for this dialog.  The framework does this automatically
//	//  when the application's main window is not a dialog
//	SetIcon(m_hIcon, TRUE);			// Set big icon
//	SetIcon(m_hIcon, FALSE);		// Set small icon
//
//	//ret = LoadUserSetting();
//
//	//if (ret == 1)
//	//{
//	//	OnBnClickedOk();
//	//}
//
//	MoleculesList = NULL;
//	InteractionsList = NULL;
//	Motif3List = NULL;
//	Motif4List = NULL;
//	ColorsAndShapesList = NULL;
//	NumberOfMolecules = 0;
//	NumberOfMotif3 = 0;
//	NumberOfMotif4 = 0;
//	NumberOfInteractions = 0;
//	ProgressCount = 1;
//	ProgressCount2 = 1;
//	DoDownstreamMaps = 0;
//	WebSiteFinishedFlag = 0;
//
//	CButton* pButtonViewer = (CButton*) GetDlgItem(IDC_BUTTON_VIEWER);
//	pButtonViewer->EnableWindow(0);
//
//	CButton* pButtonWebSite = (CButton*) GetDlgItem(IDC_BUTTON_CREATE_WEB_SITE);
//	pButtonWebSite->EnableWindow(0);
//
//	CButton* myButton;
//
//	myButton = (CButton*) GetDlgItem(IDC_BUTTON_MOTIFS_INPUT);
//	myButton->EnableWindow(0);
//
//	myButton = (CButton*) GetDlgItem(IDC_BUTTON_VALIDATE);
//	myButton->EnableWindow(0);
//
//
//	myButton = (CButton*) GetDlgItem(IDC_BUTTON15);
//	myButton->EnableWindow(0);
//
//	myButton = (CButton*) GetDlgItem(IDC_BUTTON_NET);
//	myButton->EnableWindow(0);
//
//	myButton = (CButton*) GetDlgItem(IDC_BUTTON19);
//	myButton->EnableWindow(0);
//
//	myButton = (CButton*) GetDlgItem(IDC_BUTTON_CREATE_AND_DRAW_PATHWAYS);
//	myButton->EnableWindow(0);
//
//	myButton = (CButton*) GetDlgItem(IDC_BUTTON_GENERATE_PATHWAY);
//	myButton->EnableWindow(0);
//
//	myButton = (CButton*) GetDlgItem(IDC_BUTTON_MOTIFS);
//	myButton->EnableWindow(0);
//
//	CProgressCtrl* pProg = (CProgressCtrl*) GetDlgItem(IDC_PROGRESS);
//	pProg->SetRange(0, NumberOfMolecules);
//
//	CButton* pButtonSaveAs = (CButton*) GetDlgItem(IDC_BUTTON_SAVE_AS);
//	pButtonSaveAs->EnableWindow(0);
//
//	CButton* pButtonBasedOnConnectivity = (CButton*) GetDlgItem(IDC_BUTTON_BASED_ON_CONNECTIVITY);
//	pButtonBasedOnConnectivity->EnableWindow(0);
//
//	CButton* pButtonFromSourceNodes = (CButton*) GetDlgItem(IDC_BUTTON_FROM_SOURCE_NODES);
//	pButtonFromSourceNodes->EnableWindow(0);
//
//	CButton* pButtonInteractionsMatrix = (CButton*) GetDlgItem(IDC_BUTTON_INTERACTION_MATRIX);
//	pButtonInteractionsMatrix->EnableWindow(0);
//
//	CButton* pButtonShuffledNetworks = (CButton*) GetDlgItem(IDC_BUTTON_SHUFFLED_NETWORKS);
//	pButtonShuffledNetworks->EnableWindow(0);
//
//	CButton* pButtonComputeStats = (CButton*) GetDlgItem(IDC_BUTTON_CREATE_WEB_SITE2);
//	pButtonComputeStats->EnableWindow(0);
//
//	CButton* pButtonSif = (CButton*) GetDlgItem(IDC_BUTTON_SIF);
//	pButtonSif->EnableWindow(0);
//
//	Total3Names = 0;
//	Total4Names = 0;
//	Total5Names = 0;
//
//
//	int seed;
//	seed = clock();
//	srand( (unsigned) seed);
//
//	ShuffleTypeOfNetwork = 0;
//	ShuffleNumberOfNetworks = 0;
//	ShuffleIsIsland = false;
//	ShuffleCccpl = false;
//	ShuffleMotif34 = false;
//	ShuffleMotif5 = false;
//
//	Bitmap.CreateCompatibleBitmap(GetDC(), 500, 500);
//	dcMemoryImage.CreateCompatibleDC(GetDC());
//	dcMemoryImage.SelectObject(&Bitmap);
//
//	DirLevel = 0;
//
//	//download the sigfile from the net
//	//ret = TryToDownloadSigFile();
//	ret = TryToDownloadHelpFile();
//
//#ifdef HELP_FILE_AT_BEGINING
//	if (ret != -1)
//	{
//		CDialogViewer viewerDialog;
//		
//		//TurnOnAllButtons();
//		//turn on all buttons
//		viewerDialog.buttonsFlag = 1;
//		strcpy(viewerDialog.fileName, "http://amp.pharm.mssm.edu/SNAVI/help/getting_started.htm");
//		viewerDialog.DoModal();
//
//	}
//	else
//	{
//		MessageBox("Downloading help file attempt failed!");
//	}
//	//
//
//#endif
//
//	return TRUE;  // return TRUE  unless you set the focus to a control
//}

int CTestSVGDlg::LoadUserSetting()
{
	CString strValue;
	CString tempEmail;
	CDialogUserRegistration myDialog;

	int ret;

	strValue = AfxGetApp()->GetProfileString(_T("SNAVI"), _T("UserName"));

	if (strValue == "")
	{
		//display registration required and try to send it to me through e-mail
		if (myDialog.DoModal() != IDCANCEL)
		{

			//set status to trying
			AfxGetApp()->WriteProfileString(_T("SNAVI"), _T("Status"), _T("Trying"));
		}
		else
		{
			return 1;
		}

	}

		
	return 0;
}

void CTestSVGDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

int TryToDownloadSigFile(void)
{
	CString theString;
	LPTSTR strObject = new TCHAR[200];
	CString tempText = "";
	ofstream temp;
	int dwRet;
    int count = 0;
	ofstream debug;
	ofstream out;
	size_t length;
	int num;

	CInternetSession session("My Session");
	CHttpConnection* pServer = NULL;
	CHttpFile* pFile = NULL;
	CString strServerName = "amp.pharm.mssm.edu";
	CString tempUrl;
	INTERNET_PORT nPort = 80;
	
	pServer = session.GetHttpConnection(strServerName, nPort);

	try
	{

		//http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=1521331&retmode=mode
		tempUrl.Format("http://amp.pharm.mssm.edu/SNAVI/data/current.txt");
			
		tempUrl.Replace("http://amp.pharm.mssm.edu", "");

		_tcscpy(strObject, tempUrl);
			
		pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject);
			
		pFile->AddRequestHeaders("test");
		
		pFile->SendRequest();
			
		dwRet = HTTP_STATUS_OK;

		if (dwRet == HTTP_STATUS_OK)
		{		
			try 
			{
				int count = 0;
				while (pFile->ReadString(szBuff, 4096))
				{
						length = strlen(szBuff);
						szBuff[length] = 0;
						tempText = tempText + szBuff;
				}
			}
			catch (CInternetException* pEx)
			{
				return -1;
				//AfxMessageBox("You must be connected to the internet in order to download an update!");
			}
		}

		delete pFile;
	}
	catch (CInternetException* pEx)
	{
		return -1;
		//AfxMessageBox("You must be connected to the internet in order to download an update!");
	}
	if (tempText.Find("The page cannot be found") != -1)
	{
		return -1;
	}
	else
	{
		out.open("current.sig");
		out << tempText.GetBuffer();
		out.close();
		LoadNetwork("current.sig");
		return 0;
	}
}

int TryToDownloadHelpFile(void)
{
	CString theString;
	LPTSTR strObject = new TCHAR[200];
	CString tempText = "";
	ofstream temp;
	int dwRet;
    int count = 0;
	ofstream debug;
	ofstream out;
	size_t length;
	int num;

	CInternetSession session("My Session");
	CHttpConnection* pServer = NULL;
	CHttpFile* pFile = NULL;
	CString strServerName = "amp.pharm.mssm.edu";
	CString tempUrl;
	INTERNET_PORT nPort = 80;
	
	pServer = session.GetHttpConnection(strServerName, nPort);

	try
	{

		//http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=1521331&retmode=mode
		tempUrl.Format("http://amp.pharm.mssm.edu/SNAVI/help/SNAVI_um.htm");
			
		tempUrl.Replace("http://amp.pharm.mssm.edu", "");

		_tcscpy(strObject, tempUrl);
			
		pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject);
			
		pFile->AddRequestHeaders("test");
		
		pFile->SendRequest();
			
		dwRet = HTTP_STATUS_OK;

		if (dwRet == HTTP_STATUS_OK)
		{		
			try 
			{
				int count = 0;
				while (pFile->ReadString(szBuff, 4096))
				{
						length = strlen(szBuff);
						szBuff[length] = 0;
						tempText = tempText + szBuff;
				}
			}
			catch (CInternetException* pEx)
			{
				return -1;
				//AfxMessageBox("You must be connected to the internet in order to download an update!");
			}
		}

		delete pFile;
	}
	catch (CInternetException* pEx)
	{
		return -1;
		//AfxMessageBox("You must be connected to the internet in order to download an update!");
	}
	if (tempText.Find("The page cannot be found") != -1)
	{
		return -1;
	}
	else
	{
		//ofstream SNAVIUm;
		//SNAVIUm.open("SNAVI_um.htm");
		//SNAVIUm << tempText;
		//SNAVIUm.close();
		return 0;
	}
	
}

int TryToDownloadLicence(CString tempEmail)
{
	CString theString;
	LPTSTR strObject = new TCHAR[200];
	CString tempNum;
	ofstream temp;
	int dwRet;
    int count = 0;
	ofstream debug;
	size_t length;
	int num;

	CInternetSession session("My Session");
	CHttpConnection* pServer = NULL;
	CHttpFile* pFile = NULL;
	CString strServerName = "amp.pharm.mssm.edu";
	CString tempUrl;
	INTERNET_PORT nPort = 80;
	
	pServer = session.GetHttpConnection(strServerName, nPort);

	try
	{

		//http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=1521331&retmode=mode
		tempUrl.Format("http://amp.pharm.mssm.edu/users/%s", tempEmail.GetBuffer());
			
		tempUrl.Replace("http://amp.pharm.mssm.edu", "");

		_tcscpy(strObject, tempUrl);
			
		pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject);
			
		pFile->AddRequestHeaders("test");
		
		pFile->SendRequest();
			
		dwRet = HTTP_STATUS_OK;

		if (dwRet == HTTP_STATUS_OK)
		{		
			try 
			{
				int count = 0;
				while (pFile->ReadString(szBuff, 4096))
				{
						length = strlen(szBuff);
						szBuff[length] = 0;
						tempNum = szBuff;
				}
			}
			catch (CInternetException* pEx)
			{
				return -1;
				//AfxMessageBox("You must be connected to the internet in order to download an update!");
			}
		}

		delete pFile;
	}
	catch (CInternetException* pEx)
	{
		return -1;
		//AfxMessageBox("You must be connected to the internet in order to download an update!");
	}
	num = atoi(tempNum.GetBuffer());
	return num;
}
// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CTestSVGDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CTestSVGDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CTestSVGDlg::OnButton1() 
{
	return;
}

void DumpStringToSVG(CString graphString, char* fileName, int addNavigation, int downstream)
{
	USES_CONVERSION;
	HRESULT hr;
	IDOT* pIDOT;
	IDOT testObject;
	CComBSTR result;
	CString test;
	ofstream out;
	char fullFileName[100];

	strcpy(fullFileName, fileName);

	strcat(fullFileName, ".svg");

	out.open(fullFileName);

	pIDOT = &testObject;

	hr = CoInitialize(NULL);

	if (FAILED(hr)) {
		cout << "CoInitialize Failed: " << hr << "\n\n";
		exit(1);
	}
	else {
		cout << "CoInitialize succeeded\n";
	}
		
	//hr = CoCreateInstance(CLSID_DOT, NULL, CLSCTX_ALL, IID_IDOT, reinterpret_cast(&pIDOT));

	if (FAILED(hr)) {
	  cout << "CoCreateInstance Failed: " << hr << "\n\n";
	}
	else {
	  cout << "CoCreateInstance succeeded\n";
	}
		
	pIDOT->CreateDispatch(CLSID_DOT);
	
	test = pIDOT->ToSvg(graphString);

	if (addNavigation)
	{
		test = AddNavigationBars(test, downstream);
	}
 
	//while (test.Replace("clip-path=\"url(#mypathcustom)\"", "")); 

	out << test;

	out.close();

	return;	
}

void DumpStringToJPEG(CString graphString, char* fileName)
{
	USES_CONVERSION;
	HRESULT hr;
	IDOT* pIDOT;
	IDOT testObject;
	CComBSTR result;
	CString test;
	IBinaryImage temp;
	char fullFileName[100];

	strcpy(fullFileName, fileName);

	strcat(fullFileName, ".jpg");

	pIDOT = &testObject;

	hr = CoInitialize(NULL);

	if (FAILED(hr)) {
		cout << "CoInitialize Failed: " << hr << "\n\n";
		exit(1);
	}
	else {
		cout << "CoInitialize succeeded\n";
	}
		
	//hr = CoCreateInstance(CLSID_DOT, NULL, CLSCTX_ALL, IID_IDOT, reinterpret_cast(&pIDOT));

	if (FAILED(hr)) {
	  cout << "CoCreateInstance Failed: " << hr << "\n\n";
	}
	else {
	  cout << "CoCreateInstance succeeded\n";
	}
		
	pIDOT->CreateDispatch(CLSID_DOT);
	
	//temp = pIDOT->ToSVG(graphString);
	temp = pIDOT->ToJPEG(graphString);
	
	temp.Save(fullFileName);

	return;	
}

void DumpStringToGIF(CString graphString, char* fileName)
{
	USES_CONVERSION;
	HRESULT hr;
	IDOT* pIDOT;
	IDOT testObject;
	CComBSTR result;
	CString test;
	IBinaryImage temp;
	char fullFileName[100];

	strcpy(fullFileName, fileName);

	strcat(fullFileName, ".gif");

	pIDOT = &testObject;

	hr = CoInitialize(NULL);

	if (FAILED(hr)) {
		cout << "CoInitialize Failed: " << hr << "\n\n";
		exit(1);
	}
	else {
		cout << "CoInitialize succeeded\n";
	}
		
	//hr = CoCreateInstance(CLSID_DOT, NULL, CLSCTX_ALL, IID_IDOT, reinterpret_cast(&pIDOT));

	if (FAILED(hr)) {
	  cout << "CoCreateInstance Failed: " << hr << "\n\n";
	}
	else {
	  cout << "CoCreateInstance succeeded\n";
	}
		
	pIDOT->CreateDispatch(CLSID_DOT);
	
	temp = pIDOT->ToGIF(graphString);
	
	temp.Save(fullFileName);

	return;	
}


void DumpStringToPS(CString graphString, char* fileName, int addNavigation, int downstream)
{
	USES_CONVERSION;
	HRESULT hr;
	IDOT* pIDOT;
	IDOT testObject;
	CComBSTR result;
	CString test;
	ofstream out;
	char fullFileName[100];

	strcpy(fullFileName, fileName);

	strcat(fullFileName, ".ps");

	out.open(fullFileName);

	pIDOT = &testObject;

	hr = CoInitialize(NULL);

	if (FAILED(hr)) {
		cout << "CoInitialize Failed: " << hr << "\n\n";
		exit(1);
	}
	else {
		cout << "CoInitialize succeeded\n";
	}
		
	//hr = CoCreateInstance(CLSID_DOT, NULL, CLSCTX_ALL, IID_IDOT, reinterpret_cast(&pIDOT));

	if (FAILED(hr)) {
	  cout << "CoCreateInstance Failed: " << hr << "\n\n";
	}
	else {
	  cout << "CoCreateInstance succeeded\n";
	}
		
	pIDOT->CreateDispatch(CLSID_DOT);
		
	test = pIDOT->ToPS(graphString);

	if (addNavigation)
	{
		test = AddNavigationBars(test, downstream);
	}
	out << test;

	out.close();

	return;	
}

LRESULT CTestSVGDlg::OnThreadAllPathwaysFinished(WPARAM wParam, LPARAM lParam)
{
	CStatic* countLabel;

	TurnOnAllButtons();


	if (FailedToGeneratePathway == 1)
	{
		MessageBox("No pathways with the following query were found!", "Pathway Generator", MB_OK | MB_ICONINFORMATION);
		countLabel = (CStatic*) GetDlgItem(IDC_STATIC_PROGRESS);
		countLabel->SetWindowText("No pathways were found...");	
		DirLevel = 0;		
		chdir("..");

	}
	else
	{
		countLabel = (CStatic*) GetDlgItem(IDC_STATIC_PROGRESS);
		countLabel->SetWindowText("Done generating pathways...");

		StartViewer("form.htm");
		strcpy(LastViewerCall, "form.htm");
	}
	return 0;

}
LRESULT CTestSVGDlg::OnThreadWebSiteFinished(WPARAM wParam, LPARAM lParam)
{	
	WebSiteFinishedFlag = 1;

	TurnOnAllButtons();

	MessageBox("Done!", "Site is ready for viewing!", MB_OK | MB_ICONINFORMATION);

	StartViewer("index.htm");
	strcpy(LastViewerCall, "index.htm");
	return 0;
}

LRESULT CTestSVGDlg::OnUpdateAllPathwaysProgress(WPARAM wParam, LPARAM lParam)
{
	CStatic* countLabel;
	char dummy[30];
	char stringToUpdate[200];

	// adjust the progress bar based on the global
	CProgressCtrl* pProg = (CProgressCtrl*) GetDlgItem(IDC_PROGRESS);
	
	pProg->SetPos(ProgressCount2);

	strcpy(stringToUpdate, "Searching for pathways from ");

	strcat(stringToUpdate, GlobalSource);

	strcat(stringToUpdate, " to ");

	strcat(stringToUpdate, GlobalTarget);

	strcat(stringToUpdate, " in ");

	strcat(stringToUpdate, itoa(GlobalSteps, dummy, 10));

	strcat(stringToUpdate, " steps... ");
	
	// display how many processed 
	countLabel = (CStatic*) GetDlgItem(IDC_STATIC_PROGRESS);
	countLabel->SetWindowText(stringToUpdate);

	return 0;

	
}

LRESULT CTestSVGDlg::OnThreadMotifsSearchFinished(WPARAM wParam, LPARAM lParam)
{	
	CStatic* countLabel;

	TurnOnAllButtons();


	if (FailedToGeneratePathway == 1)
	{
		MessageBox("No pathways with the following query were found!", "Pathway Generator", MB_OK | MB_ICONINFORMATION);
		countLabel = (CStatic*) GetDlgItem(IDC_STATIC_PROGRESS);
		countLabel->SetWindowText("No pathways were found...");
	}
	else
	{
		
		countLabel = (CStatic*) GetDlgItem(IDC_STATIC_PROGRESS);
		countLabel->SetWindowText("Done searching for motifs...");

		StartViewer("motifs.htm");
		strcpy(LastViewerCall, "motifs.htm");
		//MessageBox("The web site was containing the pathways was created successfully!", "Pathway Generator", MB_OK | MB_ICONINFORMATION);
	}

	

	return 0;
}

LRESULT CTestSVGDlg::OnUpdateMotifsSearchProgress(WPARAM wParam, LPARAM lParam)
{
	CStatic* countLabel;

	ProgressCount2++;

	// adjust the progress bar based on the global
	CProgressCtrl* pProg = (CProgressCtrl*) GetDlgItem(IDC_PROGRESS);
	
	pProg->SetPos(ProgressCount2);
	
	// display how many processed 
	countLabel = (CStatic*) GetDlgItem(IDC_STATIC_PROGRESS);
	countLabel->SetWindowText(MotifsMessage);

	return 0;
	
}

LRESULT CTestSVGDlg::OnThreadBasedOnConnectivityFinished(WPARAM wParam, LPARAM lParam)
{	
	TurnOnAllButtons();
	
	CStatic* countLabel = (CStatic*) GetDlgItem(IDC_STATIC_PROGRESS);
	countLabel->SetWindowText("Done analyzing sub-networks based on connectivity...");

	StartViewer("stats_for_reduced_networks.htm");
	strcpy(LastViewerCall, "stats_for_reduced_networks.htm");
	TurnOnAllButtons();

	return 0;
}

LRESULT CTestSVGDlg::OnThreadFromSourceNodesFinished(WPARAM wParam, LPARAM lParam)
{	
	TurnOnAllButtons();
	
	CStatic* countLabel = (CStatic*) GetDlgItem(IDC_STATIC_PROGRESS);
	countLabel->SetWindowText("Done analyzing sub-networks based on connectivity...");

	StartViewer("stats_for_steps_networks.htm");
	strcpy(LastViewerCall, "stats_for_steps_networks.htm");
	TurnOnAllButtons();

	LoadNetwork(OriginalNetworkName);

	return 0;
}

LRESULT CTestSVGDlg::OnUpdateBasedOnConnectivityProgress(WPARAM wParam, LPARAM lParam)
{
	CStatic* countLabel;

	// adjust the progress bar based on the global
	CProgressCtrl* pProg = (CProgressCtrl*) GetDlgItem(IDC_PROGRESS);
	pProg->SetPos(ProgressCount2);
	
	// display how many processed 
	countLabel = (CStatic*) GetDlgItem(IDC_STATIC_PROGRESS);
	countLabel->SetWindowText(BasedOnConnectivityMessage);

	return 0;
	
}

LRESULT CTestSVGDlg::OnThreadShuffledFinished(WPARAM wParam, LPARAM lParam)
{	
	TurnOnAllButtons();
	
	CStatic* countLabel = (CStatic*) GetDlgItem(IDC_STATIC_PROGRESS);
	if (ShuffleCccpl || ShuffleMotif34 || ShuffleMotif5)
		countLabel->SetWindowText("Done analyzing shuffled networks");
	else
		countLabel->SetWindowText("Done creating shuffled networks");

	if (ShuffleCccpl || ShuffleMotif34 || ShuffleMotif5)
	{
		StartViewer("shuffled_networks_analysis.htm");
		strcpy(LastViewerCall, "shuffled_networks_analysis.htm");
	}
	TurnOnAllButtons();

	LoadNetwork(OriginalNetworkName);

	return 0;
}

LRESULT CTestSVGDlg::OnThreadProcessListFinished(WPARAM wParam, LPARAM lParam)
{
	CStatic* countLabel;

	if (NumberOfMolecules > 0)
	{
		MessageBox("A subnetwork containing your genes/proteins was successfully created!", "SNAVI", MB_OK | MB_ICONINFORMATION);
		TurnOnAllButtons();
		countLabel = (CStatic*) GetDlgItem(IDC_STATIC_PROGRESS);
		countLabel->SetWindowText("");
	}
	else
	{
		MessageBox("No connections were found!", "SNAVI", MB_OK | MB_ICONINFORMATION);
		FreeNetwork();
		CButton* pButtonGeneList = (CButton*) GetDlgItem(IDC_BUTTON_LOAD_NETWORK);
		pButtonGeneList->EnableWindow(1);

		CButton* pButtonLoadNetwork = (CButton*) GetDlgItem(IDC_BUTTON_GENE_LIST);
		pButtonLoadNetwork->EnableWindow(1);

		CButton* pButtonTwoColumns = (CButton*) GetDlgItem(IDC_BUTTON_LOAD_TWO_COLUMN);
		pButtonTwoColumns->EnableWindow(1);
	}
	return 0;
}
LRESULT CTestSVGDlg::OnUpdateProcessListProgress(WPARAM wParam, LPARAM lParam)
{
	CStatic* countLabel;

	// adjust the progress bar based on the global
	CProgressCtrl* pProg = (CProgressCtrl*) GetDlgItem(IDC_PROGRESS);
	pProg->SetPos(ProgressCount2);
	
	if (ProgressCount2 == 0)
	{
		pProg->SetRange(0, 36000);
		// display how many processed 
		countLabel = (CStatic*) GetDlgItem(IDC_STATIC_PROGRESS);
		countLabel->SetWindowText(GeneListMessage);
	}

	if (ProgressCount3 == -1)
	{
		pProg->SetRange(0, sumFact(NumberOfMatchMolecules));
		ProgressCount3 = 1;
		ProgressCount2 = 1;
	}

	if (ProgressCount3 == 1)
	{
		countLabel = (CStatic*) GetDlgItem(IDC_STATIC_PROGRESS);
		countLabel->SetWindowText(GeneListMessage);
	}
	
	return 0;
}
LRESULT CTestSVGDlg::OnUpdateShuffledProgress(WPARAM wParam, LPARAM lParam)
{
	CStatic* countLabel;

	// adjust the progress bar based on the global
	CProgressCtrl* pProg = (CProgressCtrl*) GetDlgItem(IDC_PROGRESS);
	pProg->SetPos(ProgressCount2);
	
	// display how many processed 
	countLabel = (CStatic*) GetDlgItem(IDC_STATIC_PROGRESS);
	countLabel->SetWindowText(BasedOnConnectivityMessage);

	return 0;
	
}

LRESULT CTestSVGDlg::OnUpdateFromSourceNodesProgress(WPARAM wParam, LPARAM lParam)
{
	CStatic* countLabel;
	char stringToUpdate[400];

	strcpy(stringToUpdate, FromSourceNodesMessage);
	// adjust the progress bar based on the global
	CProgressCtrl* pProg = (CProgressCtrl*) GetDlgItem(IDC_PROGRESS);
	pProg->SetPos(ProgressCount2);
	
	// display how many processed 
	countLabel = (CStatic*) GetDlgItem(IDC_STATIC_PROGRESS);
	countLabel->SetWindowText(stringToUpdate);

	return 0;
	
}
LRESULT CTestSVGDlg::OnUpdateWebSiteProgress(WPARAM wParam, LPARAM lParam)
{
	CStatic* countLabel;
	char dummy[30];
	char stringToUpdate[200];
	
	// adjust the progress bar based on the global
	CProgressCtrl* pProg = (CProgressCtrl*) GetDlgItem(IDC_PROGRESS);
	
	if (ProgressCount2 == 1)
	{
		strcpy(stringToUpdate, "Performing the network statistical analysis... please wait!");
		pProg->SetPos(1);
	}
	else
	{
		strcpy(stringToUpdate, "Created web pages for ");

		strcat(stringToUpdate, itoa(ProgressCount2 - 2, dummy, 10));

		strcat(stringToUpdate, " molecules out of ");

		strcat(stringToUpdate, itoa(NumberOfMolecules, dummy, 10));

		strcat(stringToUpdate, " molecules.");

		pProg->SetPos(ProgressCount2 + 1);

	}

	
	// display how many processed 
	countLabel = (CStatic*) GetDlgItem(IDC_STATIC_PROGRESS);
	countLabel->SetWindowText(stringToUpdate);

	return 0;
}

/* add a node or add a count if already there */
MOLECULE* AddToMoleculesWithLink(char* name, char* accHuman, char* accMouse, char* type, char* location, int link)
{			
	MOLECULE* tempNode;
	bool linkAlreadyThere = FALSE;
	int i;

    /* if the list is empty */
    if (!MoleculesList)
    {
         /* just store this information */
	    MoleculesList = (MOLECULE*) malloc(sizeof(MOLECULE));
	    MoleculesList->linksCount = 1;
        strcpy(MoleculesList->name, name);
		strcpy(MoleculesList->moleculeType, type);
		strcpy(MoleculesList->accHuman, accHuman);
		strcpy(MoleculesList->accMouse, accMouse);
		strcpy(MoleculesList->location, location);
	    MoleculesList->next = 0;
        MoleculesList->number =  NumberOfMolecules + 1;
		if (link != 0)
		{
			MoleculesList->linksTo[0] = link;
		}
		else
		{
			MoleculesList->linksTo[0] = NumberOfMolecules + 2;
		}
	    NumberOfMolecules++;
	    return MoleculesList;	
    }
    
    
    /* look for a match or loop all the way to the end */
    tempNode = MoleculesList;

    /* loop until a match was found or the end */
    while ((tempNode->next != 0) && (strcmp(tempNode->name, name)))
    {
	    tempNode = tempNode->next;
    }

    /* if a match was found add one to the count */
    if (!strcmp(tempNode->name, name))
    {
		/* check if the link is already there */
		for (i = 0; i < tempNode->linksCount; i++)
		{
			if (tempNode->linksTo[i] == link)
			{
				linkAlreadyThere = TRUE;
				break;
			}
		}
		if (!linkAlreadyThere)
		{
			if (link != 0)
			{
				tempNode->linksCount++;
				tempNode->linksTo[tempNode->linksCount - 1] = link;
			}
			else
			{
				tempNode->linksCount++;
				tempNode->linksTo[tempNode->linksCount - 1] = NumberOfMolecules + 1;
			}
		}

		return MoleculesList;
    }
    
    /* just store this information in a new node */
    tempNode->next = (MOLECULE*) malloc(sizeof(MOLECULE));
    tempNode = tempNode->next;
    tempNode->next = 0;
    tempNode->linksCount = 1;
    strcpy(tempNode->name, name);
	strcpy(tempNode->moleculeType, type);
	strcpy(tempNode->accHuman, accHuman);
	strcpy(tempNode->accMouse, accMouse);
	strcpy(tempNode->location, location);
    tempNode->number = NumberOfMolecules + 1;

	if (link != 0)
	{
		tempNode->linksTo[0] = link;
	}
	else
	{
		tempNode->linksTo[0] = NumberOfMolecules + 2;
	}
    NumberOfMolecules++;

    return MoleculesList;  
}

INTERACTION* AddToInteractions(char* source, char* sourceAccHuman, char* sourceAccMouse, char* sourceLocation, char* sourceType, char* target, char* targetAccHuman, char* targetAccMouse,
							   char* targetLocation, char* targetType, char* effect, char* typeOfInteraction, int pmid)
{
	INTERACTION* tempNode;
	bool referenceAlreadyThere = FALSE;
	int i;
	char doubleTypeOfInteraction[200];
	char doubleEffect[200];
	char doublePubMedID[200];

    /* if the list is empty */
    if (!InteractionsList)
    {
         /* just store this information */
	    InteractionsList = (INTERACTION*) malloc(sizeof(INTERACTION));
	    InteractionsList->referenceCount = 1;
		InteractionsList->references[0] = pmid;
        strcpy(InteractionsList->source, source);
		strcpy(InteractionsList->sourceAccHuman, sourceAccHuman);
		strcpy(InteractionsList->sourceAccMouse, sourceAccMouse);
		strcpy(InteractionsList->sourceLocation, sourceLocation);
		strcpy(InteractionsList->sourceType, sourceType);
		strcpy(InteractionsList->target, target);
		strcpy(InteractionsList->targetAccHuman, targetAccHuman);
		strcpy(InteractionsList->targetAccMouse, targetAccMouse);
		strcpy(InteractionsList->targetLocation, targetLocation);
		strcpy(InteractionsList->targetType, targetType);
		strcpy(InteractionsList->effect, effect);
		strcpy(InteractionsList->typeOfInteraction, typeOfInteraction);
		InteractionsList->pmid = pmid;
	    InteractionsList->next = 0;
        InteractionsList->number =  NumberOfInteractions + 1;
	    NumberOfInteractions++;
	    return InteractionsList;	
    }
    
    
    /* look for a match or loop all the way to the end */
    tempNode = InteractionsList;

    /* loop until a match was found or the end */
    while (!(((!strcmp(tempNode->source, source)) && (!strcmp(tempNode->target, target)))))
    {
		if (tempNode->next == 0)
		{
			break;
		}
		tempNode = tempNode->next;
    }

    /* if a match was found add one to the count */
    if (((!strcmp(tempNode->source, source)) && (!strcmp(tempNode->target, target))))
    {
		/* check if the link is already there */
		for (i = 0; i < tempNode->referenceCount; i++)
		{
			if (tempNode->references[i] == pmid)
			{
				sprintf(doublePubMedID, "The PubMed ID: %d is used twice to describe the interaction between %s and %s!", pmid, tempNode->source, tempNode->target); 
				//AfxMessageBox(doublePubMedID);
				referenceAlreadyThere = TRUE;
				break;
			}
		}
		if (!referenceAlreadyThere)
		{
			tempNode->referenceCount++;
			tempNode->references[tempNode->referenceCount - 1] = pmid;

			if (strcmp(tempNode->effect, effect))
			{
				sprintf(doubleEffect, "The effect %s and not the effect %s was previously is used to describe the interaction between %s and %s!", tempNode->effect, effect, tempNode->source, tempNode->target); 
				//AfxMessageBox(doubleEffect);
			}
			if (strcmp(tempNode->typeOfInteraction, typeOfInteraction))
			{
				sprintf(doubleTypeOfInteraction, "The interaction %s and not the interaction %s was previously is used to describe the interaction between %s and %s!", tempNode->typeOfInteraction, typeOfInteraction, tempNode->source, tempNode->target); 
				//AfxMessageBox(doubleTypeOfInteraction);
			}
		}

		return InteractionsList;
    }
    
    /* just store this information in a new node */
    tempNode->next = (INTERACTION*) malloc(sizeof(INTERACTION));
	tempNode = tempNode->next;
    tempNode->referenceCount = 1;
	tempNode->references[0] = pmid;
    strcpy(tempNode->source, source);
	strcpy(tempNode->sourceAccHuman, sourceAccHuman);
	strcpy(tempNode->sourceAccMouse, sourceAccMouse);
	strcpy(tempNode->sourceLocation, sourceLocation);
	strcpy(tempNode->sourceType, sourceType);
	strcpy(tempNode->target, target);
	strcpy(tempNode->targetAccHuman, targetAccHuman);
	strcpy(tempNode->targetAccMouse, targetAccMouse);
	strcpy(tempNode->targetLocation, targetLocation);
	strcpy(tempNode->targetType, targetType);
	strcpy(tempNode->effect, effect);
	strcpy(tempNode->typeOfInteraction, typeOfInteraction);
	tempNode->pmid = pmid;
	tempNode->next = 0;
    tempNode->number = NumberOfInteractions + 1;
	NumberOfInteractions++;

    return InteractionsList;  	
}

void CTestSVGDlg::OnButtonLoadNetwork() 
{
	ifstream inputFile;
    int ret;
	
	static char BASED_CODE szFilter[] = "SIG Files (*.sig)|*.sig|Text Files (*.txt)|*.txt|All Files (*.*)|*.*||";

	CFileDialog myDialog(TRUE, NULL, "*.sig", OFN_OVERWRITEPROMPT, szFilter, NULL );

	ret = myDialog.DoModal();

	if (ret == IDCANCEL)
	{
		return;
	}
    
	strcpy(OriginalNetworkName, myDialog.m_ofn.lpstrFile);

	FreeNetwork();

    ret = LoadNetwork(myDialog.m_ofn.lpstrFile);
	
	SortMoleculeList();

	if (ret == 0)
	{
		MessageBox("The network was loaded successfully!", "Loading the network", MB_OK | MB_ICONINFORMATION);
	}
	else if (ret == -1)
	{
		MessageBox("Failed to load network, bad file name!", "Error!", MB_OK | MB_ICONINFORMATION);
		return;
	}
	else if (ret == -2)
	{
		MessageBox("The network was loaded successfully!\nThe colors and shapes file (colors_and_shapes.txt) is empty or missing!\nPut this file in the same directory as the *.sig file.", "Loading the network", MB_OK | MB_ICONINFORMATION);
	}
	
	TurnOnAllButtons();


	inputFile.close();


    return;
}

void CountInAndOutLinks(void)
{
	MOLECULE* tempMol;
	MOLECULE* tempMol1;
	MOLECULE* tempMol2;
	INTERACTION* tempInteraction;

	tempMol = MoleculesList;

	while (tempMol)
	{
		tempMol->inLinksCount = 0;
		tempMol->outLinksCount = 0;
		tempMol->positiveLinksCount = 0;
		tempMol->negativeLinksCount = 0;
		tempMol->positiveInLinksCount = 0;
		tempMol->negativeInLinksCount = 0;
		tempMol->positiveOutLinksCount = 0;
		tempMol->negativeOutLinksCount = 0;
		tempMol->neutralLinksCount = 0;
		tempMol->totalLinksCount = 0;

		tempMol = tempMol->next;
	}

	tempInteraction = InteractionsList;

	while (tempInteraction)
	{
		tempMol1 = GetNodeBasedOnName(tempInteraction->source);
		tempMol2 = GetNodeBasedOnName(tempInteraction->target);
		
		if (!strcmp(tempInteraction->effect, "0"))
		{
			tempMol1->totalLinksCount++;
			tempMol2->totalLinksCount++;
			tempMol1->neutralLinksCount++;
			tempMol2->neutralLinksCount++;
		}
		else
		{
			tempMol1->outLinksCount++;
			tempMol2->inLinksCount++;
			tempMol1->totalLinksCount++;
			tempMol2->totalLinksCount++;

			if (!strcmp(tempInteraction->effect, "+"))
			{
				tempMol1->positiveLinksCount++;
				tempMol1->positiveOutLinksCount++;
				tempMol2->positiveLinksCount++;
				tempMol2->positiveInLinksCount++;
			}
			else
			{
				tempMol1->negativeLinksCount++;
				tempMol1->negativeOutLinksCount++;
				tempMol2->negativeLinksCount++;
				tempMol2->negativeInLinksCount++;
			}
		}	
		tempInteraction = tempInteraction->next;
	}
	return;
}

int GetNumberBasedOnString(char* name)
{
    MOLECULE* tempNode;

	if (!MoleculesList)
	{
		return 0;
	}
	/* look for a match or loop all the way to the end */
    tempNode = MoleculesList;

    /* loop until a match was found or the end */
    while ((tempNode->next != 0) && (strcmp(tempNode->name, name)))
    {
	    tempNode = tempNode->next;
    }

	if (!strcmp(tempNode->name, name))
	{
		return tempNode->number;
	}
	else 
	{
		return 0;
	}
}

int GetNumberBasedOnStringFromListToDraw(char* name)
{
    MOLECULE* tempNode;

	if (!ListToDraw)
	{
		return 0;
	}
	/* look for a match or loop all the way to the end */
    tempNode = ListToDraw;

    /* loop until a match was found or the end */
    while ((tempNode->next != 0) && (strcmp(tempNode->name, name)))
    {
	    tempNode = tempNode->next;
    }

	if (!strcmp(tempNode->name, name))
	{
		return tempNode->number;
	}
	else 
	{
		return 0;
	}
}

void CTestSVGDlg::OnButtonCreateWebSite() 
{

	ShutOffAllButtons();

	ProgressCount2 = 0;

	if (DirLevel == 0)
	{
		DirLevel = 1;
	}
	else
	{
		chdir("..");	
	}
	mkdir("SNAVI_website");
	chdir("SNAVI_website");
	
	// start the thread that computes 
	pThreadCreateWebSite = AfxBeginThread(CreateWebSiteThread,
								GetSafeHwnd(), 
								THREAD_PRIORITY_BELOW_NORMAL);

}


UINT CreateWebSiteThread(LPVOID pParam)
{
	MOLECULE* tempNode;
	ofstream htmlParent;
	char linksFromParent[1000];

	htmlParent.open("network.html");
	htmlParent << "<HTML><BODY>" << endl;
	
	ProgressCount2++;

	::PostMessage((HWND) pParam, WM_UPDATEWEBSITEPROGRESS, 0, 0);

	if (NumberOfMolecules < 2000)
	{
		CreateStatisticalAnalysisWebPage();
	}

	::PostMessage((HWND) pParam, WM_UPDATEWEBSITEPROGRESS, 0, 0);

	CreateIndexPage();

	MakeMachinesSVGMap("network");

	tempNode = MoleculesList;

	while (tempNode)
	{	
		sprintf(linksFromParent, "<A HREF=\"%s.svg\">%s</A>", tempNode->name, tempNode->name);

		htmlParent << linksFromParent << "<BR>" << endl;
		
		if (DoDownstreamMaps)
		{
			MakeDownstreamSVGFile(tempNode->name);
			MakeDownstreamNetFile(tempNode->name);
			MakeDownstreamHTMLFile(tempNode->name);
		}
		

		MakeSVGFile(tempNode->name);

		//MakeGifFile(tempNode->name);

		MakeHTMLFile(tempNode->name);

		//MakePrintableHTMLFile(tempNode->name);

		tempNode = tempNode->next;
		
		ProgressCount2++;

		::PostMessage((HWND) pParam, WM_UPDATEWEBSITEPROGRESS, 0, 0);
		
	}

	htmlParent << "</BODY></HTML>" << endl;
	
	if (NumberOfMolecules < 2000)
	{
		CreateStatisticalAnalysisWebPage();
	}

	CreateIndexPage();

	::PostMessage((HWND) pParam, WM_UPDATEWEBSITEPROGRESS, 0, 0);
	
	//MakeBigSVGMap();


	//ComputeBestLocationsForVisio();

	//MakeTextForVisio();

	ProgressCount2++;

	::PostMessage((HWND) pParam, WM_UPDATEWEBSITEPROGRESS, 0, 0);

	CreateColorsAndShape();

	CreateMainWebPage();

	::PostMessage((HWND) pParam, WM_THREADWEBSITEFINISHED, 0, 0);

	return 0;

}

void MakeBigSVGMap(void)
{
	CString graphString;
	INTERACTION* tempInteractionNode;
	MOLECULE* tempNode;

	graphString = "digraph G {";
	graphString += "size=\"37.5,50\";";
	graphString += "concentrate=false;\n";
	//graphString += "rankdir=LR";

	
	

	//graphString += "subgraph cluster0 {";
	//graphString += "style=filled;\n";
	//graphString += "color=azure1;\n";
	//graphString += "rank=source;\n";
	//graphString += "label=\"MEMBRANE\";\n";

	graphString += " { ";
	tempNode = MoleculesList;
	while (tempNode)
	{
		graphString +=  tempNode->name;
		graphString += " [style=\"filled\", URL=\"";
		graphString +=	tempNode->name;
		graphString +=	".htm\"";
		
		graphString += " shape=\"";
		graphString += GetShape(tempNode->name);
		graphString += "\", color=\"";
		graphString += GetColor(tempNode->name);
		graphString += "\"];\n";
		tempNode = tempNode->next;		
	}
	
	graphString += " } \n";
	

	tempInteractionNode = InteractionsList;

	while (tempInteractionNode)
	{
		graphString +=  tempInteractionNode->source;
		graphString +=  " -> ";
		graphString +=  tempInteractionNode->target;
			
		if (!strcmp(tempInteractionNode->effect, "+"))
		{
			graphString += " [arrowhead=\"normal\", color=\"darkgreen\"] ";
		}
		else if (!strcmp(tempInteractionNode->effect, "_"))
		{
			graphString += " [arrowhead=\"tee\",arrowsize=\"3.0\", color=\"red1\"] ";
		}
		else if (!strcmp(tempInteractionNode->effect, "0"))
		{
			graphString += " [arrowhead=\"box\",arrowtail=\"box\", color=\"blue1\"] ";
		}
		graphString +=  ";";
		
		tempInteractionNode = tempInteractionNode->next;
	}

	graphString += "}";

	//DumpToDot(graphString, "network");
	//DumpStringToJPEG(graphString, "network");	
	DumpStringToSVG(graphString, "network", 1, 0);
}

void MakeMachinesSVGMap(char* fileName)
{
	CString graphString;
	MOLECULE* tempNode;
	CString titleLigands;
	CString titleMembrane;
	CString titleCentral;
	CString titleVesicles;
	CString titleTranslation;
	CString titleTranscription;
	CString titleApoptosis;
	CString titleCytoskeleton;
	CString titleChannels;
	int ligands = 0;
	int membrane = 0;
	int central = 0;
	int vesicles = 0;
	int translation = 0;
	int transcription = 0;
	int apoptosis = 0;
	int cytoskeleton = 0;
	int channels = 0;
	
	ofstream outExtracellular;
	ofstream outMotility;
	ofstream outTranscription;
	ofstream outTranslation;
	ofstream outMembrane;
	ofstream outApoptosis;
	ofstream outChannel;
	ofstream outVesicles;
	ofstream outCentral;

	outExtracellular.open("ligands.htm");
	outMotility.open("cytoskeleton.htm");
	outTranscription.open("transcription.htm");
	outTranslation.open("translation.htm");
	outMembrane.open("membrane.htm");
	outApoptosis.open("apoptosis.htm");
	outChannel.open("channels.htm");
	outVesicles.open("vesicles.htm");
	outCentral.open("central.htm");

	outExtracellular << "<html><body><table>\n";
	outMotility << "<html><body><table>\n";
	outTranscription << "<html><body><table>\n";
	outTranslation << "<html><body><table>\n";
	outMembrane << "<html><body><table>\n";
	outApoptosis << "<html><body><table>\n";
	outChannel << "<html><body><table>\n";
	outVesicles << "<html><body><table>\n";
	outCentral << "<html><body><table>\n";

	outExtracellular << "<TR><TD><B>Name</B></TD><TD><B>Type</B></TD><TD><B>Location</B></TD><TD><B>Links</B></TD><TD><B>In Links</B></TD><TD><B>Out Links</B></TD><TD><B>CC</B></TD><TD><B>Avg. Path Length</B></TD>";
	outMotility << "<TR><TD><B>Name</B></TD><TD><B>Type</B></TD><TD><B>Location</B></TD><TD><B>Links</B></TD><TD><B>In Links</B></TD><TD><B>Out Links</B></TD><TD><B>CC</B></TD><TD><B>Avg. Path Length</B></TD>";
	outTranscription << "<TR><TD><B>Name</B></TD><TD><B>Type</B></TD><TD><B>Location</B></TD><TD><B>Links</B></TD><TD><B>In Links</B></TD><TD><B>Out Links</B></TD><TD><B>CC</B></TD><TD><B>Avg. Path Length</B></TD>";
	outTranslation << "<TR><TD><B>Name</B></TD><TD><B>Type</B></TD><TD><B>Location</B></TD><TD><B>Links</B></TD><TD><B>In Links</B></TD><TD><B>Out Links</B></TD><TD><B>CC</B></TD><TD><B>Avg. Path Length</B></TD>";
	outMembrane << "<TR><TD><B>Name</B></TD><TD><B>Type</B></TD><TD><B>Location</B></TD><TD><B>Links</B></TD><TD><B>In Links</B></TD><TD><B>Out Links</B></TD><TD><B>CC</B></TD><TD><B>Avg. Path Length</B></TD>";
	outApoptosis << "<TR><TD><B>Name</B></TD><TD><B>Type</B></TD><TD><B>Location</B></TD><TD><B>Links</B></TD><TD><B>In Links</B></TD><TD><B>Out Links</B></TD><TD><B>CC</B></TD><TD><B>Avg. Path Length</B></TD>";
	outChannel << "<TR><TD><B>Name</B></TD><TD><B>Type</B></TD><TD><B>Location</B></TD><TD><B>Links</B></TD><TD><B>In Links</B></TD><TD><B>Out Links</B></TD><TD><B>CC</B></TD><TD><B>Avg. Path Length</B></TD>";
	outVesicles << "<TR><TD><B>Name</B></TD><TD><B>Type</B></TD><TD><B>Location</B></TD><TD><B>Links</B></TD><TD><B>In Links</B></TD><TD><B>Out Links</B></TD><TD><B>CC</B></TD><TD><B>Avg. Path Length</B></TD>";
	outCentral << "<TR><TD><B>Name</B></TD><TD><B>Type</B></TD><TD><B>Location</B></TD><TD><B>Links</B></TD><TD><B>In Links</B></TD><TD><B>Out Links</B></TD><TD><B>CC</B></TD><TD><B>Avg. Path Length</B></TD>";

	
	tempNode = MoleculesList;

	while (tempNode)
	{
		if (!strcmp(tempNode->moleculeType, "Ligand"))
		{
			outExtracellular << "<TR><TD><A HREF=\"" << tempNode->name << ".htm\">" << tempNode->name << "</A></TD><TD>" << tempNode->moleculeType;
			outExtracellular << "</TD><TD>" << tempNode->location << "</TD><TD>" << tempNode->linksCount << "</TD><TD>" << tempNode->inLinksCount << "</TD><TD>" << tempNode->outLinksCount << "</TD><TD>" << tempNode->cc << "</TD><TD>" << tempNode->avgPathLength;
		
			ligands++;
		}
		else if (!strcmp(tempNode->moleculeType, "Cytoskeleton"))
		{
			outMotility << "<TR><TD><A HREF=\"" << tempNode->name << ".htm\">" << tempNode->name << "</A></TD><TD>" << tempNode->moleculeType;
			outMotility << "</TD><TD>" << tempNode->location << "</TD><TD>" << tempNode->linksCount << "</TD><TD>" << tempNode->inLinksCount << "</TD><TD>" << tempNode->outLinksCount << "</TD><TD>" << tempNode->cc << "</TD><TD>" << tempNode->avgPathLength;
		
			cytoskeleton++;
		}
		else if (!strcmp(tempNode->moleculeType, "TF"))
		{
			outTranscription << "<TR><TD><A HREF=\"" << tempNode->name << ".htm\">" << tempNode->name << "</A></TD><TD>" << tempNode->moleculeType;
			outTranscription << "</TD><TD>" << tempNode->location << "</TD><TD>" << tempNode->linksCount << "</TD><TD>" << tempNode->inLinksCount << "</TD><TD>" << tempNode->outLinksCount << "</TD><TD>" << tempNode->cc << "</TD><TD>" << tempNode->avgPathLength;
		
			transcription++;
		}
		else if ((!strcmp(tempNode->location, "ER")) ||
				(!strcmp(tempNode->location, "Ribosomes")))
		{
			outTranslation << "<TR><TD><A HREF=\"" << tempNode->name << ".htm\">" << tempNode->name << "</A></TD><TD>" << tempNode->moleculeType;
			outTranslation << "</TD><TD>" << tempNode->location << "</TD><TD>" << tempNode->linksCount << "</TD><TD>" << tempNode->inLinksCount << "</TD><TD>" << tempNode->outLinksCount << "</TD><TD>" << tempNode->cc << "</TD><TD>" << tempNode->avgPathLength;
		
			translation++;
		}
		else if ((!strcmp(tempNode->location, "Mitochondria")) ||
			    (!strcmp(tempNode->moleculeType, "Protease")))
		{
			outApoptosis << "<TR><TD><A HREF=\"" << tempNode->name << ".htm\">" << tempNode->name << "</A></TD><TD>" << tempNode->moleculeType;
			outApoptosis << "</TD><TD>" << tempNode->location << "</TD><TD>" << tempNode->linksCount << "</TD><TD>" << tempNode->inLinksCount << "</TD><TD>" << tempNode->outLinksCount << "</TD><TD>" << tempNode->cc << "</TD><TD>" << tempNode->avgPathLength;
		
			apoptosis++;
		}
		else if (!strcmp(tempNode->location, "Vesicles"))
		{
			outVesicles << "<TR><TD><A HREF=\"" << tempNode->name << ".htm\">" << tempNode->name << "</A></TD><TD>" << tempNode->moleculeType;
			outVesicles << "</TD><TD>" << tempNode->location << "</TD><TD>" << tempNode->linksCount << "</TD><TD>" << tempNode->inLinksCount << "</TD><TD>" << tempNode->outLinksCount << "</TD><TD>" << tempNode->cc << "</TD><TD>" << tempNode->avgPathLength;
		
			vesicles++;
		}
		else if (!strcmp(tempNode->moleculeType, "Channel"))
		{
			outChannel << "<TR><TD><A HREF=\"" << tempNode->name << ".htm\">" << tempNode->name << "</A></TD><TD>" << tempNode->moleculeType;
			outChannel << "</TD><TD>" << tempNode->location << "</TD><TD>" << tempNode->linksCount << "</TD><TD>" << tempNode->inLinksCount << "</TD><TD>" << tempNode->outLinksCount << "</TD><TD>" << tempNode->cc << "</TD><TD>" << tempNode->avgPathLength;
		
			channels++;
		}
		else if (!strcmp(tempNode->location, "Membrane"))
		{
			outMembrane << "<TR><TD><A HREF=\"" << tempNode->name << ".htm\">" << tempNode->name << "</A></TD><TD>" << tempNode->moleculeType;
			outMembrane << "</TD><TD>" << tempNode->location << "</TD><TD>" << tempNode->linksCount << "</TD><TD>" << tempNode->inLinksCount << "</TD><TD>" << tempNode->outLinksCount << "</TD><TD>" << tempNode->cc << "</TD><TD>" << tempNode->avgPathLength;
		
			membrane++;
		}
		else
		{
			outCentral << "<TR><TD><A HREF=\"" << tempNode->name << ".htm\">" << tempNode->name << "</A></TD><TD>" << tempNode->moleculeType;
			outCentral << "</TD><TD>" << tempNode->location << "</TD><TD>" << tempNode->linksCount << "</TD><TD>" << tempNode->inLinksCount << "</TD><TD>" << tempNode->outLinksCount << "</TD><TD>" << tempNode->cc << "</TD><TD>" << tempNode->avgPathLength;
		
			central++;
		}
		
		tempNode = tempNode->next;
	}

	outExtracellular << "</table></body></html>\n";
	outMotility << "</table></body></html>\n";
	outTranscription << "</table></body></html>\n";
	outTranslation << "</table></body></html>\n";
	outMembrane << "</table></body></html>\n";
	outApoptosis << "</table></body></html>\n";
	outChannel << "</table></body></html>\n";
	outVesicles << "</table></body></html>\n";
	outCentral << "</table></body></html>\n";

	outExtracellular.close();
	outMotility.close();
	outTranscription.close();
	outTranslation.close();
	outMembrane.close();
	outApoptosis.close();
	outChannel.close();
	outVesicles.close();
	outCentral.close();

	//apoptosis = apoptosis + 9;
	//central = central - 9;

	graphString = "digraph G {";
	graphString += "size=\"7,7\";";
	graphString += "concentrate=false;\n";

	graphString += " { ";

	titleLigands.Format("\"Extracellular Ligands (%d)\"", ligands);
	graphString +=  titleLigands;
	graphString += " [style=\"filled\", URL=\"";
	graphString +=	"ligands.htm\"";
	
	graphString += " shape=\"";
	graphString += "invhouse";
	graphString += "\", color=\"";
	graphString += "lightskyblue1";
	graphString += "\"];\n";		
	
	titleMembrane.Format("\"Membrane (%d)\"", membrane);
	graphString +=  titleMembrane;
	graphString += " [style=\"filled\", URL=\"";
	graphString +=	"membrane.htm\"";
	
	graphString += " shape=\"";
	graphString += "box";
	graphString += "\", color=\"";
	graphString += "greenyellow";
	graphString += "\"];\n";

	titleCentral.Format("\"Central Signaling Network (%d)\"", central);
	graphString +=  titleCentral;
	graphString += " [style=\"filled\", URL=\"";
	graphString +=	"central.htm\"";
	
	graphString += " shape=\"";
	graphString += "box";
	graphString += "\", color=\"";
	graphString += "turquoise";
	graphString += "\"];\n";

	titleVesicles.Format("\"Secretion (%d)\"", vesicles);
	graphString +=  titleVesicles;
	graphString += " [style=\"filled\", URL=\"";
	graphString +=	"vesicles.htm\"";
	
	graphString += " shape=\"";
	graphString += "box";
	graphString += "\", color=\"";
	graphString += "lightgray";
	graphString += "\"];\n";

	titleApoptosis.Format("\"Apoptosis (%d)\"", apoptosis);
	graphString +=  titleApoptosis;
	graphString += " [style=\"filled\", URL=\"";
	graphString +=	"apoptosis.htm\"";
	
	graphString += " shape=\"";
	graphString += "box";
	graphString += "\", color=\"";
	graphString += "sienna3";
	graphString += "\"];\n";

	titleTranslation.Format("\"Translation (%d)\"", translation);
	graphString +=  titleTranslation;
	graphString += " [style=\"filled\", URL=\"";
	graphString +=	"translation.htm\"";
	
	graphString += " shape=\"";
	graphString += "box";
	graphString += "\", color=\"";
	graphString += "azure2";
	graphString += "\"];\n";

	titleTranscription.Format("\"Transcription (%d)\"", transcription);
	graphString +=  titleTranscription;
	graphString += " [style=\"filled\", URL=\"";
	graphString +=	"transcription.htm\"";
	
	graphString += " shape=\"";
	graphString += "box";
	graphString += "\", color=\"";
	graphString += "pink2";
	graphString += "\"];\n";

	titleCytoskeleton.Format("\"Cytoskeleton (%d)\"", cytoskeleton);
	graphString +=  titleCytoskeleton;
	graphString += " [style=\"filled\", URL=\"";
	graphString +=	"cytoskeleton.htm\"";
	
	graphString += " shape=\"";
	graphString += "box";
	graphString += "\", color=\"";
	graphString += "khaki1";
	graphString += "\"];\n";

	titleChannels.Format("\"Electrical response (%d)\"", channels);
	graphString +=  titleChannels;
	graphString += " [style=\"filled\", URL=\"";
	graphString +=	"channels.htm\"";
	
	graphString += " shape=\"";
	graphString += "box";
	graphString += "\", color=\"";
	graphString += "limegreen";
	graphString += "\"];\n";

	graphString += " } \n";
	

	graphString +=  titleLigands;
	graphString +=  " -> ";
	graphString +=  titleMembrane;
	graphString += " [arrowhead=\"normal\", color=\"darkgreen\"]; ";

	graphString +=  titleMembrane;
	graphString +=  " -> ";
	graphString +=  titleCentral;
	graphString += " [arrowhead=\"normal\", color=\"darkgreen\"]; ";

	graphString +=  titleCentral;
	graphString +=  " -> ";
	graphString +=  titleChannels;
	graphString += " [arrowhead=\"normal\", color=\"darkgreen\"]; ";

	graphString +=  titleCentral;
	graphString +=  " -> ";
	graphString +=  titleVesicles;
	graphString += " [arrowhead=\"normal\", color=\"darkgreen\"]; ";

	graphString +=  titleCentral;
	graphString +=  " -> ";
	graphString +=  titleTranscription;
	graphString += " [arrowhead=\"normal\", color=\"darkgreen\"]; ";

	graphString +=  titleCentral;
	graphString +=  " -> ";
	graphString +=  titleTranslation;
	graphString += " [arrowhead=\"normal\", color=\"darkgreen\"]; ";

	graphString +=  titleCentral;
	graphString +=  " -> ";
	graphString +=  titleApoptosis;
	graphString += " [arrowhead=\"normal\", color=\"darkgreen\"]; ";

	graphString +=  titleCentral;
	graphString +=  " -> ";
	graphString +=  titleCytoskeleton;
	graphString += " [arrowhead=\"normal\", color=\"darkgreen\"]; ";

	graphString += "}";

	//DumpStringToJPEG(graphString, "network");
	DumpStringToSVG(graphString, "network", 0 , 0);
}



void MakeSVGMapBasedOnVisited(char* fileName)
{
	int count = 0;
	INTERACTION* tempInteractionNode;
	MOLECULE* tempNode;
	CString graphString;

	graphString = "";
	graphString = "digraph G {";
	graphString += "size=\"8,8\";";
	graphString += "concentrate=true;\n";
	//graphString += "rank=max;\n";

	graphString += " { ";
	
	tempInteractionNode = InteractionsList;

	while (tempInteractionNode)
	{
		if (tempInteractionNode->flag)
		{
			tempNode = GetNodeBasedOnName(tempInteractionNode->source);
			tempNode->visited = 1;
			tempNode = GetNodeBasedOnName(tempInteractionNode->target);
			tempNode->visited = 1;
		}
		tempInteractionNode = tempInteractionNode->next;
	}
	
	
	tempNode = MoleculesList;
	while (tempNode)
	{
		if (tempNode->visited == 1)
		{
			graphString +=  tempNode->name;
			graphString += " [style=\"filled\", URL=\"";
			graphString +=	tempNode->name;
			graphString +=	".htm\"";
		
			graphString += " shape=\"";
			graphString += GetShape(tempNode->name);
			graphString += "\", color=\"";
			graphString += GetColor(tempNode->name);
			graphString += "\"];\n";
			
			count++;
		}
		tempNode = tempNode->next;
	}

	graphString += " } \n";
	

	tempInteractionNode = InteractionsList;

	while (tempInteractionNode)
	{

		if (tempInteractionNode->flag)
		{
			graphString +=  tempInteractionNode->source;
			graphString +=  " -> ";
			graphString +=  tempInteractionNode->target;
			
			if (!strcmp(tempInteractionNode->effect, "+"))
			{
				graphString += " [arrowhead=\"normal\", color=\"darkgreen\"] ";
			}
			else if (!strcmp(tempInteractionNode->effect, "_"))
			{
				graphString += " [arrowhead=\"tee\",arrowsize=\"3.0\", color=\"red1\"] ";
			}
			else if (!strcmp(tempInteractionNode->effect, "0"))
			{
				graphString += " [arrowhead=\"box\",arrowtail=\"box\", color=\"blue1\"] ";
			}
			graphString +=  ";";
		}
		tempInteractionNode = tempInteractionNode->next;
	}

	graphString += "}";

	if (count > 12)
	{
		DumpStringToSVG(graphString, fileName, 1, 2);
	}
	else
	{
		DumpStringToSVG(graphString, fileName, 0, 0);
	}
	//DumpStringToJPEG(graphString, fileName);
}


void DumpToDot(CString graphString, char* fileName)
{

	ofstream out;
	char file[100];
	
	strcpy(file, fileName);

	strcat(file, ".dot");

	out.open(file);

	out << graphString;

	out.close();
}

void MakeSVGFile(char* name)
{
	CString graphString;
	INTERACTION* tempInteractionNode;
	int count = 0;

	tempInteractionNode = InteractionsList;
	graphString = "digraph G {";
	graphString += "size=\"7.5,10\";";
	while (tempInteractionNode)
	{
		if ((!strcmp(tempInteractionNode->source, name)) || (!strcmp(tempInteractionNode->target, name)))
		{
			count++;
			graphString = AddThisInteraction(tempInteractionNode, graphString);
		}
		tempInteractionNode = tempInteractionNode->next;
	}

	graphString += "}";

	if (count > 12)
	{
		DumpStringToSVG(graphString, name, 1, 2);
	}
	else
	{
		DumpStringToSVG(graphString, name, 0, 0);
	}
}

void MakeGifFile(char* name)
{
	CString graphString;
	INTERACTION* tempInteractionNode;

	tempInteractionNode = InteractionsList;
	graphString = "digraph G {";
	graphString += "size=\"7.5,10\";";
	while (tempInteractionNode)
	{
		if ((!strcmp(tempInteractionNode->source, name)) || (!strcmp(tempInteractionNode->target, name)))
		{
			graphString = AddThisInteraction(tempInteractionNode, graphString);
		}
		tempInteractionNode = tempInteractionNode->next;
	}

	graphString += "}";

	DumpStringToGIF(graphString, name);
}

CString AddNavigationBars(CString svgFileWithoutNavigation, int downstream)
{
	CString tempString;
	ifstream template1;
	ifstream template2;
	ofstream out;
	CString temp1;
	CString temp2;

	tempString = svgFileWithoutNavigation;

	//tempString.Replace("svg width", "svg onload=\"init(evt)\" width");
	tempString.Replace("svg width", "!--");
	tempString.Replace("xmlns:xlink=\"http://www.w3.org/1999/xlink\">", "--><svg onload=\"init(evt)\" width=\"735px\" height=\"600px\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n");
	if (downstream == 2)
	{
		temp1 = "xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n<script type=\"text/ecmascript\">\n<![CDATA[\nvar svgDocument;\nvar zoomAmt;\nvar xOffset;\nvar yOffset;\nvar scale;\nvar maxScale;\nvar imageWidth;\nvar imageHeight;\nfunction init(evt)\n{\n    svgDocument = evt.getTarget().getOwnerDocument();\n    zoomAmt = 0;\n    xOffset = 0;\n    yOffset = 60;\n    scale = 0.8;\n    maxScale = 10;\n    imageWidth = 742;\n    imageHeight = 606;\n    panRestore();\n    //panUp();\n}\nfunction transformMap ()\n{\n    var obj = svgDocument.getElementById(\"Pathway\");\n    var centerX = imageWidth  / 2.0;\n    var centerY = imageHeight / 2.0;\n    var adjustX = (-centerX * (scale - 0.8)) + xOffset;\n    var adjustY = (-centerY * (scale - 0.8)) + yOffset;\n    var transParms = 'translate(' + adjustX + ',' + adjustY + ') ';\n    transParms += 'scale(' + scale + ')';\n    // alert(transParms);\n    obj.setAttribute(\"transform\", transParms); \n}\nfunction click_node(id)\n{\n    var testx = parent.click_node;\n    if (typeof(testx) == \"function\")\n    {\n		parent.click_node(id);\n    }\n}\nfunction click_relation(id)\n{\n    var testx = parent.click_relation;\n    if (typeof(testx) == \"function\")\n    {\n        parent.click_relation(id);\n    }\n}\nfunction click_pathway(toId, fromId)\n{\n    var testx = parent.click_pathway;\n    if (typeof(testx) == \"function\")\n    {\n	parent.click_pathway(toId, fromId);\n    }\n}\nfunction check_interpath(evt, pathid)\n{\n  var obj = evt.getTarget();\n  var testx = parent.is_frompath;\n  var child = obj.firstChild;\n  if (typeof(testx) == \"function\")\n  {\n    if (parent.is_frompath(pathid))\n    {\n      while (child != null)\n      {\n        if (child.nodeType == 1)\n        {\n          if ((child.localName == \"g\") || (child.localName == \"polyline\"))\n          {\n            child.setAttribute(\"style\", \"fill:none;stroke:red\");\n          }\n          else if (child.localName == \"polygon\")\n          {\n            child.setAttribute(\"style\", \"fill:red;stroke:red\");\n          }\n        }\n        child = child.nextSibling;\n      }\n    }\n  }\n}\nfunction set_status (msg)\n{\n ";
		temp1 += "var obj = svgDocument.getElementById(\"status_text\");\n  var child;\n \n  child = obj.firstChild;\n  if ((child != null) && (child.nodeType == 3))\n  {\n    if ((msg != null) && (msg.length > 0))\n    {\n      child.data = msg;\n    }\n    else\n    {\n";
		temp1 += "child.data = \" \";\n    }\n  }\n}\nfunction zoomIn ()\n{\n    scale = scale + 0.8;\n    if (scale > maxScale)\n    {\n       scale = maxScale;\n    }\n    transformMap();\n    panUp();\n    panUp();\n    panUp();\n    panUp();\n    panUp();\n    panUp();\n    panUp();\n    panUp();\n    panUp();\n    panUp();\n    panUp();\n    panUp();\n}\nfunction zoomOut ()\n{\n    scale = scale - 0.8;\n    if (scale < 0.8)\n    {\n       scale = 0.8;\n    }\n    transformMap();\n    panDown();\n    panDown();\n    panDown();\n    panDown();\n    panDown();\n    panDown();\n    panDown();\n    panDown();\n    panDown();\n    panDown();\n    panDown();\n    panDown();\n}\nfunction panUp ()\n{\n    yOffset = yOffset + 20;\n    transformMap();\n}\nfunction panDown ()\n{\n    yOffset = yOffset - 20;\n    transformMap();\n}\nfunction panLeft ()\n{\n    xOffset = xOffset + 20;\n    transformMap();\n}\nfunction panRight ()\n{\n    xOffset = xOffset - 20;\n    transformMap();\n}\nfunction panRestore ()\n{\n    xOffset = 0;\n    yOffset = 0;\n    scale = 0.5;\n    //obj = svgDocument.getElementById(\"zoom\");\n    //obj.setAttribute(\"x1\", 0);\n    //obj.setAttribute(\"x2\", 0);\n    transformMap();    \n}\nfunction doHighlight (evt, msg)\n{\n  var obj = evt.getTarget();\n  obj.setAttribute(\"fill\", \"rgb(239,24,33)\");\n  set_status(msg);\n}\nfunction resetHighlight (evt)\n{\n  var obj = evt.getTarget();\n  obj.setAttribute(\"fill\", \"rgb(99,154,206)\");\n  set_status(\" \");\n}\n// ]]>\n</script>\n<defs>\n<clipPath id=\"theClip\">\n<polygon points=\"1 61, 741 61, 741 665, 1 665\"\nstyle=\"fill: none;\"/>\n</clipPath>\n</defs>\n<!-- viewport outline -->\n<rect x=\"0\" y=\"61\" width=\"742\" height=\"606\"\nstyle=\"stroke: black; stroke-width: 1; fill: none;\"/>\n<!-- pathway graph style=\"clip-path: url(#theClip);\" -->\n<g style=\"clip-path: url(#theClip);\">\n<g id=\"Pathway\"  transform=\"translate(0,60)\">\n<!-- prefile.include ends, begin pathway graph -->\n<g id=\"stkecm;CMP_10705\" class=\"graph\">\n</g>";

		//template1.open("template1a.txt");
	}
	else if (downstream == 1)
	{
		temp1 = "xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n<script type=\"text/ecmascript\">\n<![CDATA[\nvar svgDocument;\nvar zoomAmt;\nvar xOffset;\nvar yOffset;\nvar scale;\nvar maxScale;\nvar imageWidth;\nvar imageHeight;\nfunction init(evt)\n{\n    svgDocument = evt.getTarget().getOwnerDocument();\n    zoomAmt = 0;\n    xOffset = 0;\n    yOffset = 60;\n    scale = 0.8;\n    maxScale = 10;\n    imageWidth = 742;\n    imageHeight = 606;\n    panRestore();\n    //panUp();\n}\nfunction transformMap ()\n{\n    var obj = svgDocument.getElementById(\"Pathway\");\n    var centerX = imageWidth  / 2.0;\n    var centerY = imageHeight / 2.0;\n    var adjustX = (-centerX * (scale - 0.8)) + xOffset;\n    var adjustY = (-centerY * (scale - 0.8)) + yOffset;\n    var transParms = 'translate(' + adjustX + ',' + adjustY + ') ';\n    transParms += 'scale(' + scale + ')';\n    // alert(transParms);\n    obj.setAttribute(\"transform\", transParms); \n}\nfunction click_node(id)\n{\n    var testx = parent.click_node;\n    if (typeof(testx) == \"function\")\n    {\n		parent.click_node(id);\n    }\n}\nfunction click_relation(id)\n{\n    var testx = parent.click_relation;\n    if (typeof(testx) == \"function\")\n  ";
		temp1 += "{\n        parent.click_relation(id);\n    }\n}\nfunction click_pathway(toId, fromId)\n{\n    var testx = parent.click_pathway;\n    if (typeof(testx) == \"function\")\n    {\n	parent.click_pathway(toId, fromId);\n    }\n}\nfunction check_interpath(evt, pathid)\n{\n  var obj = evt.getTarget();\n  var testx = parent.is_frompath;\n  var child = obj.firstChild;\n  if (typeof(testx) == \"function\")\n  {\n    if (parent.is_frompath(pathid))\n    {\n      while (child != null)\n      {\n        if (child.nodeType == 1)\n        {\n          if ((child.localName == \"g\") || (child.localName == \"polyline\"))\n          {\n            child.setAttribute(\"style\", \"fill:none;stroke:red\");\n          }\n          else if (child.localName == \"polygon\")\n          {\n            child.setAttribute(\"style\", \"fill:red;stroke:red\");\n          }\n        }\n        child = child.nextSibling;\n      }\n    }\n  }\n}\nfunction set_status (msg)\n{\n  var obj = svgDocument.getElementById(\"status_text\");\n  var child;\n \n  child = obj.firstChild;\n  if ((child != null) && (child.nodeType == 3))\n  {\n    if ((msg != null) && (msg.length > 0))\n    {\n      child.data = msg;\n    }\n    else\n    {\n      child.data = \" \";\n    }\n  }\n}\nfunction zoomIn ()\n{\n    scale = scale + 0.8;\n    if (scale > maxScale)\n    {\n       scale = maxScale;\n    }\n    transformMap();\n}\nfunction zoomOut ()\n{\n    scale = scale - 0.8;\n    if (scale < 0.8)\n    {\n       scale = 0.8;\n    }\n    transformMap();\n}\nfunction panUp ()\n{\n    yOffset = yOffset + 20;\n    transformMap();\n}\nfunction panDown ()\n{\n    yOffset = yOffset - 20;\n    transformMap();\n}\nfunction panLeft ()\n{\n  ";
		temp1 += "xOffset = xOffset + 20;\n    transformMap();\n}\nfunction panRight ()\n{\n    xOffset = xOffset - 20;\n    transformMap();\n}\nfunction panRestore ()\n{\n    xOffset = 120;\n    yOffset = 150;\n    scale = 0.5;	    \n \n    //obj = svgDocument.getElementById(\"zoom\");\n    //obj.setAttribute(\"x1\", 0);\n    //obj.setAttribute(\"x2\", 0);\n    transformMap();    \n}\nfunction doHighlight (evt, msg)\n{\n  var obj = evt.getTarget();\n  obj.setAttribute(\"fill\", \"rgb(239,24,33)\");\n  set_status(msg);\n}\nfunction resetHighlight (evt)\n{\n  var obj = evt.getTarget();\n  obj.setAttribute(\"fill\", \"rgb(99,154,206)\");\n  set_status(\" \");\n}\n// ]]>\n</script>\n<defs>\n<clipPath id=\"theClip\">\n<polygon points=\"1 61, 741 61, 741 665, 1 665\"\nstyle=\"fill: none;\"/>\n</clipPath>\n</defs>\n<!-- viewport outline -->\n<rect x=\"0\" y=\"61\" width=\"742\" height=\"606\"\nstyle=\"stroke: black; stroke-width: 1; fill: none;\"/>\n<!-- pathway graph style=\"clip-path: url(#theClip);\" -->\n<g style=\"clip-path: url(#theClip);\">\n<g id=\"Pathway\"  transform=\"translate(0,60)\">\n<!-- prefile.include ends, begin pathway graph -->\n<g id=\"stkecm;CMP_10705\" class=\"graph\">\n</g>";

		//template1.open("template1b.txt");
	}
	else
	{	
		temp1 = "xmlns:xlink=\"dummy line\nxmlns:xlink=\"http://www.w3.org/1999/xlink\">\n<script type=\"text/ecmascript\">\n<![CDATA[\nvar svgDocument;\nvar zoomAmt;\nvar xOffset;\nvar yOffset;\nvar scale;\nvar maxScale;\nvar imageWidth;\nvar imageHeight;\nfunction init(evt)\n{\n    svgDocument = evt.getTarget().getOwnerDocument();\n    zoomAmt = 0;\n    xOffset = 0;\n    yOffset = 60;\n    scale = 0.2;\n    maxScale = 10;\n    imageWidth = 742;\n    imageHeight = 606;\n    panRestore();\n}\nfunction transformMap ()\n{\n    var obj = svgDocument.getElementById(\"Pathway\");\n    var centerX = imageWidth  / 2.0;\n    var centerY = imageHeight / 2.0;\n    var adjustX = (-centerX * (scale - 0.2)) + xOffset;\n    var adjustY = (-centerY * (scale - 0.2)) + yOffset;\n    var transParms = 'translate(' + centerX + ',' + centerY + ') ';\n    transParms += 'scale(' + scale + ')';\n    // alert(transParms);\n    obj.setAttribute(\"transform\", transParms); \n}\nfunction click_node(id)\n{\n    var testx = parent.click_node;\n    if (typeof(testx) == \"function\")\n    {\n		parent.click_node(id);\n    }\n}\nfunction click_relation(id)\n{\n    var testx = parent.click_relation;\n    if (typeof(testx) == \"function\")\n    {\n        parent.click_relation(id);\n    }\n}\nfunction click_pathway(toId, fromId)\n{\n    var testx = parent.click_pathway;\n    if (typeof(testx) == \"function\")\n   ";
		temp1 += "{\n	parent.click_pathway(toId, fromId);\n    }\n}\nfunction check_interpath(evt, pathid)\n{\n  var obj = evt.getTarget();\n  var testx = parent.is_frompath;\n  var child = obj.firstChild;\n  if (typeof(testx) == \"function\")\n  {\n    if (parent.is_frompath(pathid))\n    {\n      while (child != null)\n      {\n        if (child.nodeType == 1)\n        {\n          if ((child.localName == \"g\") || (child.localName == \"polyline\"))\n          {\n            child.setAttribute(\"style\", \"fill:none;stroke:red\");\n          }\n          else if (child.localName == \"polygon\")\n          {\n            child.setAttribute(\"style\", \"fill:red;stroke:red\");\n          }\n        }\n        child = child.nextSibling;\n      }\n    }\n  }\n}\nfunction set_status (msg)\n{\n  var obj = svgDocument.getElementById(\"status_text\");\n  var child;\n \n  child = obj.firstChild;\n  if ((child != null) && (child.nodeType == 3))\n  {\n    if ((msg != null) && (msg.length > 0))\n    {\n      child.data = msg;\n    }\n    else\n    {\n      child.data = \" \";\n    }\n  }\n}\nfunction zoomIn ()\n{\n    scale = scale + 0.2;\n    if (scale > maxScale)\n    {\n       scale = maxScale;\n    }\n    transformMap();\n}\nfunction zoomOut ()\n{\n    scale = scale - 0.2;\n    if (scale < 0.2)\n    {\n       scale = 0.2;\n    }\n    transformMap();\n}\nfunction panUp ()\n{\n ";
		temp1 += "yOffset = yOffset + 50;\n    transformMap();\n}\nfunction panDown ()\n{\n    yOffset = yOffset - 50;\n    transformMap();\n}\nfunction panLeft ()\n{\n    xOffset = xOffset + 50;\n    transformMap();\n}\nfunction panRight ()\n{\n    xOffset = xOffset - 50;\n    transformMap();\n}\nfunction panRestore ()\n{\n    xOffset = 120;\n    yOffset = 90;\n    scale = 0.5;\n    //obj = svgDocument.getElementById(\"zoom\");\n    //obj.setAttribute(\"x1\", 0);\n    //obj.setAttribute(\"x2\", 0);\n    //yOffset = yOffset + 40;\n    transformMap();    \n}\nfunction doHighlight (evt, msg)\n{\n  var obj = evt.getTarget();\n  obj.setAttribute(\"fill\", \"rgb(239,24,33)\");\n  set_status(msg);\n}\nfunction resetHighlight (evt)\n{\n  var obj = evt.getTarget();\n  obj.setAttribute(\"fill\", \"rgb(99,154,206)\");\n  set_status(\" \");\n}\n// ]]>\n</script>\n<defs>\n<clipPath id=\"theClip\">\n<polygon points=\"1 61, 741 61, 741 665, 1 665\"\nstyle=\"fill: none;\"/>\n</clipPath>\n</defs>\n<!-- viewport outline -->\n<rect x=\"0\" y=\"61\" width=\"742\" height=\"606\"\nstyle=\"stroke: black; stroke-width: 1; fill: none;\"/>\n<!-- pathway graph style=\"clip-path: url(#theClip);\" -->\n<g style=\"clip-path: url(#theClip);\">\n<g id=\"Pathway\"  transform=\"translate(0,60)\">\n<!-- prefile.include ends, begin pathway graph -->\n<g id=\"stkecm;CMP_10705\" class=\"graph\">\n</g>";
	}

	tempString.Replace("xmlns:xlink=\"http://www.w3.org/1999/xlink\">", "XXXXXXXXXX");

	tempString.Replace("XXXXXXXXXX", temp1); 

	temp2 = "</g></g></g>\n<!-- navigation controls -->\n<g id=\"navbox\">\n	<rect x=\"0\" y=\"0\" width=\"742\" height=\"60\"\n		 style=\"fill:rgb(206,207,206);stroke:rgb(0,0,0);stroke-width:1\"/>\n\n	<polygon id=\"pan_right\"\n        onmouseup=\"panRight()\"\n        onmouseover=\"doHighlight(evt, 'Click to pan to the right')\"\n        onmouseout=\"resetHighlight(evt)\"\n		points=\"28.0732,13 32,20.5 28.0732,28 28.0732,23.4412 25,23.4412 25,17.4118 28.0732,17.4118\"\n		 transform=\"matrix(3.39111 0 0 2.98838 -12.6265 -29.7101)\"\n         fill=\"rgb(99,154,206)\"\n		 style=\"stroke:rgb(0,0,0);stroke-width:0.5\"/>\n	<polygon id=\"pan_left\"\n        onmouseup=\"panLeft()\"\n        onmouseover=\"doHighlight(evt, 'Click to pan to the left')\"\n        onmouseout=\"resetHighlight(evt)\"\n		points=\"123.991,25 120.064,32.5 123.991,40 123.991,35.4412 127.064,35.4412 127.064,29.4118\n			123.991,29.4118\" transform=\"matrix(3.39111 0 0 2.98838 -404.865 -65.5706)\"\n         fill=\"rgb(99,154,206)\"\n		 style=\"stroke:rgb(0,0,0);stroke-width:0.5\"/>\n	<polygon id=\"pan_down\"\n        onmouseup=\"panDown()\"\n        onmouseover=\"doHighlight(evt, 'Click to pan down')\"\n        onmouseout=\"resetHighlight(evt)\"\n		points=\"116.032,32.0408 123.532,35.9678 131.032,32.0408 126.473,32.0408 126.473,28.9678 120.444,28.9678\n			120.444,32.0408\" transform=\"matrix(3.39111 0 0 2.98838 -369.822 -50.6287)\"\n         fill=\"rgb(99,154,206)\"\n		 style=\"stroke:rgb(0,0,0);stroke-width:0.5\"/>\n	<polygon id=\"pan_up\"\n        onmouseup=\"panUp()\"\n  ";
	temp2 += "onmouseover=\"doHighlight(evt, 'Click to pan up')\"\n        onmouseout=\"resetHighlight(evt)\"\n		points=\"116.032,32.0408 123.532,35.9678 131.032,32.0408 126.473,32.0408 126.473,28.9678 120.444,28.9678\n			120.444,32.0408\" transform=\"matrix(3.39111 0 0 -2.98838 -369.823 111.74)\"\n         fill=\"rgb(99,154,206)\"\n		 style=\"stroke:rgb(0,0,0);stroke-width:0.5\"/>\n	<g id=\"go_home\" \n         onmouseup=\"panRestore()\" \n         onmouseover=\"doHighlight(evt, 'Click to restore graph to original position')\"\n         onmouseout=\"resetHighlight(evt)\"\n         fill=\"rgb(99,154,206)\"\n         transform=\"matrix(1 0 0 1 0 -0.333333)\">\n		<rect x=\"196\" y=\"11\" width=\"26\" height=\"26\"\n			transform=\"translate(-19.1111 -2.66667)\"\n			 style=\"stroke:rgb(0,0,0);stroke-width:1\"/>\n		<line x1=\"182\" y1=\"16\" x2=\"182\" y2=\"28\"\n			transform=\"matrix(1 0 0 1 2.22222 0.444444)\"\n			 style=\"fill:none;stroke:rgb(0,0,0);stroke-width:2\"/>\n		<line x1=\"187\" y1=\"22\" x2=\"187\" y2=\"28\"\n			transform=\"matrix(1 0 0 1 2.22222 0.444444)\"\n			 style=\"fill:none;stroke:rgb(0,0,0);stroke-width:2\"/>\n	";
	temp2 += "<line x1=\"192\" y1=\"13\" x2=\"192\" y2=\"28\"\n			transform=\"matrix(1 0 0 1 2.22222 0.444444)\"\n			 style=\"fill:none;stroke:rgb(0,0,0);stroke-width:2\"/>\n		<line x1=\"182\" y1=\"28\" x2=\"192\" y2=\"28\"\n			transform=\"matrix(1 0 0 1 2.22222 0.444444)\"\n	";
	temp2 += "style=\"fill:none;stroke:rgb(0,0,0);stroke-width:2\"/>\n		<line x1=\"189\" y1=\"12\" x2=\"179\" y2=\"21\"\n			 style=\"fill:none;stroke:rgb(0,0,0);stroke-width:2\"/>\n		<line x1=\"188\" y1=\"12\" x2=\"199\" y2=\"20\"\n			 style=\"fill:none;stroke:rgb(0,0,0);stroke-width:2\"/>\n	</g>\n	<g id=\"zoom_out\" onmouseup=\"zoomOut()\" \n             onmouseover=\"doHighlight(evt, 'Click to zoom out')\"\n             onmouseout=\"resetHighlight(evt)\"\n             fill=\"rgb(99,154,206)\"\n             transform=\"matrix(1 0 0 1 0 0)\">\n		<rect x=\"116\" y=\"8\" width=\"26\" height=\"26\"\n			 style=\"stroke:rgb(0,0,0);stroke-width:1\"/>\n		<ellipse cx=\"126\" cy=\"18\" rx=\"6\" ry=\"6\"\n			 style=\"stroke:rgb(0,0,0);stroke-width:1\"/>\n		<line x1=\"130\" y1=\"23\" x2=\"137\" y2=\"29\"\n			transform=\"matrix(1 0 0 1 0.888889 -0.888889)\"\n			 style=\"fill:none;stroke:rgb(0,0,0);stroke-width:2\"/>\n		<line x1=\"123\" y1=\"18\" x2=\"129\" y2=\"18\"\n			 style=\"fill:none;stroke:rgb(0,0,0);stroke-width:2\"/>\n	</g>\n	<g id=\"zoom_in\" onmouseup=\"zoomIn()\" \n             onmouseover=\"doHighlight(evt, 'Click to zoom in')\"\n             onmouseout=\"resetHighlight(evt)\"\n             fill=\"rgb(99,154,206)\"\n             transform=\"matrix(1 0 0 1 0.888889 -0.444444)\">\n		<rect x=\"116\" y=\"8\" width=\"26\" height=\"26\"\n			transform=\"matrix(1 0 0 1 29.7778 0.444444)\"\n			 style=\"stroke:rgb(0,0,0);stroke-width:1\"/>\n		<ellipse cx=\"126\" cy=\"18\" rx=\"6\" ry=\"6\"\n			transform=\"matrix(1 0 0 1 29.7778 0.444444)\"\n			 style=\"stroke:rgb(0,0,0);stroke-width:1\"/>\n		<line x1=\"130\" y1=\"23\" x2=\"137\" y2=\"29\"\n			transform=\"matrix(1 0 0 1 30.6667 -0.444445)\"\n		";
	temp2 += "style=\"fill:none;stroke:rgb(0,0,0);stroke-width:2\"/>\n		<line x1=\"123\" y1=\"18\" x2=\"129\" y2=\"18\"\n			transform=\"matrix(1 0 0 1 29.7778 0.444444)\"\n			 style=\"fill:none;stroke:rgb(0,0,0);stroke-width:2\"/>\n		<line x1=\"156\" y1=\"15\" x2=\"156\" y2=\"22\"\n			 style=\"fill:none;stroke:rgb(0,0,0);stroke-width:2\"/>\n	</g>\n	<g>\n		<rect x=\"117\" y=\"40\" width=\"452\" height=\"14\"\n			transform=\"matrix(1.54201 0 0 1 -64.1436 -0.222222)\"\n			 style=\"fill:rgb(192,192,192);stroke:rgb(0,0,0);stroke-width:1\"/>\n		<text id=\"status_text\" x=\"183px\" y=\"48px\"\n			transform=\"matrix(1 0 0 1 -63.5556 3.00778)\"\n			 style=\"fill:rgb(0,0,0);font-size:14;font-family:Arial\"> </text>\n	</g>\n</g>	\n</svg>";

	tempString.Replace("</g></svg>", temp2);

	out << tempString;

	out.close();

	return tempString;
}

void MakeHTMLFile(char* name)
{
	ofstream out;
	INTERACTION* tempInteractionNode;
	MOLECULE* tempMolecule;
	int i, j;
	int ret;
	CString authors;
	CString title;
	CString year;
	CString journal;
	CString volume;
	CString pages;
	ofstream refs;

	j = 1;
	tempInteractionNode = InteractionsList;

	char fileName[1000];

	strcpy(fileName, name);

	strcat(fileName, ".htm");
	
	out.open(fileName);

	out << "<HTML><BODY>";

	out << "<CENTER><H3>" << name << "</H3></CENTER>" << endl;
	
	tempMolecule = GetNodeBasedOnName(name);

	out << "<CENTER>" << "<EMBED SRC=\"" << name << ".svg\" width=\"740\" height=\"300\" type=\"image/svg+xml\" /></CENTER>" << endl;
	out << "<BR>";

	

	if (DoDownstreamMaps)
	{
		out << "<CENTER>" << "<A HREF=\"" << name << "_ds_map.htm\">View the downstream map for this component...</A></CENTER><BR>" << endl;
		out << "<CENTER><B>Number of downstream effectors: </B>" << tempMolecule->numberOfDownstreamEffectors << " out of " << NumberOfMolecules << "</CENTER>" << endl;
	}

	out << "<CENTER><B>Average path length to all other components: </B>" << tempMolecule->avgPathLength << "<BR>" << endl;
	out << "<B>Clustering coefficient: </B>" << tempMolecule->cc << "<BR>" << endl;
	out << "<B>Grid coefficient: </B>" << tempMolecule->gc << "<BR>" << endl;

	if (strlen(tempMolecule->accHuman) == 6)
	{
		out << "<BR><B>Swiss-Prot Human Accession Code: </B>" << "<A HREF=\"http://au.expasy.org/cgi-bin/niceprot.pl?" << tempMolecule->accHuman << "\">" << tempMolecule->accHuman << "</A>" << endl;
		out << "<BR><B>Swiss-Prot Mouse Accession Code: </B>" << "<A HREF=\"http://au.expasy.org/cgi-bin/niceprot.pl?" << tempMolecule->accMouse << "\">" << tempMolecule->accMouse << "</A>" << "</CENTER><BR>" << endl;
	}
	else
	{
		out << "</CENTER><BR>" << endl;
	}

	out << "<B><U>List of interactions:</U></B><BR><BR>" << endl;

	while (tempInteractionNode)
	{
		if ((!strcmp(tempInteractionNode->source, name)) || (!strcmp(tempInteractionNode->target, name)))
		{
			out << "<B>Source:</B><A HREF=\"" << tempInteractionNode->source << ".htm\">" << tempInteractionNode->source << "</A>  ";
			out << "<B>Type of molecule:</B>" << tempInteractionNode->sourceType << "  ";
			out << "<B>Location:</B>" << tempInteractionNode->sourceLocation << "  " << "<BR>";
			out << "<B>Target:</B><A HREF=\"" << tempInteractionNode->target << ".htm\">" << tempInteractionNode->target << "</A>   ";
			out << "<B>Type of molecule:</B>" << tempInteractionNode->targetType << "  ";
			out << "<B>Location:</B>" << tempInteractionNode->targetLocation << "  " << "<BR>";
			out << "<B>Type of interaction:</B>" << tempInteractionNode->typeOfInteraction << "  ";
			out << "<B>Effect:</B>" << tempInteractionNode->effect << "<BR>";
			out << "<B>References:</B><BR>" << endl;

			for (i = 0; i < tempInteractionNode->referenceCount; i++)
			{
				ret = DownLoadAbstractInTextForPubMedID(tempInteractionNode->references[i]);
				
				if (ret == 0)
				{
					GetAuthorScienceFormat(tempInteractionNode->references[i], authors);
					GetJournalScienceFormat(tempInteractionNode->references[i], journal);
					GetVolumeScienceFormat(tempInteractionNode->references[i], volume);
					GetPagesScienceFormat(tempInteractionNode->references[i], pages);
					GetYearScienceFormat(tempInteractionNode->references[i], year);
					DeletePubMedIdFile(tempInteractionNode->references[i]);
				}

				out << "<tr><td>" << i + 1 << ". </td><td>";
				
				if (ret == 0)
				{
					out << authors << " " << journal << " " << volume << " " << pages << " (" << year << ").";
				}

				out << " PubMed ID: " << endl; 	
				out << "<A HREF=\"http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?cmd=Retrieve&db=pubmed&dopt=Abstract&list_uids=";
				out << tempInteractionNode->references[i] << "\">";
				out << tempInteractionNode->references[i] << "</A><BR>";
			}
		
			out << "<BR>";
		}
		tempInteractionNode = tempInteractionNode->next;
	} 

	out << "</BODY></HTML>" << endl;
}

void MakePrintableHTMLFile(char* name)
{

}

int LoadColorsAndShapes(void)
{
	ifstream inputFile;
	ofstream outputFile;
	COLORS_AND_SHAPES* tempNode;
	int count = 0;

	inputFile.open("colors_and_shapes.txt", ios::in);

	if (!inputFile.fail())
	{
		while (!inputFile.eof())
		{		
			if (!count)
			{
				ColorsAndShapesList = (COLORS_AND_SHAPES*) malloc(sizeof(COLORS_AND_SHAPES));
				tempNode = ColorsAndShapesList;
			}
			else
			{
				tempNode->next = (COLORS_AND_SHAPES*) malloc(sizeof(COLORS_AND_SHAPES));
				tempNode = tempNode->next;
			}
			tempNode->next = 0;

			inputFile >> tempNode->name >> tempNode->color >> tempNode->shape;
			count++;
		}
	}

	if ((count == 1) || (count == 0))
	{	
		free(ColorsAndShapesList);
		ColorsAndShapesList = 0;
		count = 0;

		inputFile.close();
		outputFile.open("colors_and_shapes.txt");
		outputFile << "Ligand red ellipse" << endl;
		outputFile << "Channel lawngreen ellipse" << endl;
		outputFile << "CellAdhesion lawngreen ellipse" << endl;
		outputFile << "Cytoskeleton yellow1 ellipse" << endl;
		outputFile << "Activator turquoise ellipse" << endl;
		outputFile << "NEF turquoise ellipse" << endl;
		outputFile << "DualFunction violet ellipse" << endl;
		outputFile << "Kinase turquoise ellipse" << endl;
		outputFile << "Adapter turquoise ellipse" << endl;
		outputFile << "Lipid turquoise ellipse" << endl;
		outputFile << "Receptor limegreen ellipse" << endl;
		outputFile << "TF pink2 ellipse" << endl;
		outputFile << "Ribosome pink3 ellipse" << endl;
		outputFile << "GTPase turquoise ellipse" << endl;
		outputFile << "Phosphatase turquoise ellipse" << endl;
		outputFile << "Cool turquoise ellipse" << endl;
		outputFile << "Messenger turquoise ellipse" << endl;
		outputFile << "Cyclase limegreen ellipse" << endl;
		outputFile << "Phospholipase turquoise ellipse" << endl;
		outputFile << "RNA pink3 ellipse" << endl;
		outputFile << "Bcl2Family sienna3 ellipse" << endl;
		outputFile << "PDE turquoise ellipse" << endl;
		outputFile << "Inhibitor turquoise ellipse" << endl;
		outputFile << "Synthase turquoise ellipse" << endl;
		outputFile << "Vesicle purple1 ellipse" << endl;
		outputFile << "Ubiquitinase turquoise ellipse" << endl;
		outputFile << "Protease sienna3 ellipse" << endl;
		outputFile << "DNase sienna3 ellipse" << endl;
		outputFile << "Lipase turquoise ellipse" << endl;
		outputFile << "Gprotein turquoise ellipse" << endl;
		outputFile << "GAP turquoise ellipse" << endl;
		outputFile << "default turquoise ellipse";

		outputFile.close();

		return -1;
	}

	inputFile.close();
	return 0;
}

char* GetColor(char* name)
{
	COLORS_AND_SHAPES* tempNode;
	MOLECULE* tempMolecule;
	char localName[200];

	tempMolecule = MoleculesList;

	while ((tempMolecule) && (strcmp(name, tempMolecule->name)))
	{
		tempMolecule = tempMolecule->next;
	}

	if (tempMolecule)
	{
		strcpy(localName, tempMolecule->moleculeType);
	}
	else
	{
		strcpy(localName, "default");
	}
		
	tempNode = ColorsAndShapesList;

	while ((tempNode) && (strcmp(localName, tempNode->name)) && (strcmp(name, tempNode->name)))
	{
		tempNode = tempNode->next;
	}
	
	if (tempNode)
	{
		return tempNode->color;
	}
	else
	{
		tempNode = ColorsAndShapesList;
		while ((tempNode) && (strcmp("default", tempNode->name)))
		{
			tempNode = tempNode->next;
		}
		if (tempNode)
		{
			return tempNode->color;
		}
		else
		{
			return DefaultColor;
		}
	}
}

char* GetShape(char* name)
{
	COLORS_AND_SHAPES* tempNode;
	MOLECULE* tempMolecule;
	char localName[200];

	tempMolecule = MoleculesList;

	while ((tempMolecule) && (strcmp(name, tempMolecule->name)))
	{
		tempMolecule = tempMolecule->next;
	}

	if (tempMolecule)
	{
		strcpy(localName, tempMolecule->moleculeType);
	}
	else
	{
		strcpy(localName, "default");
	}
		
	tempNode = ColorsAndShapesList;

	while ((tempNode) && (strcmp(localName, tempNode->name)) && (strcmp(name, tempNode->name)))
	{
		tempNode = tempNode->next;
	}
	
	if (tempNode)
	{
		return tempNode->shape;
	}
	else
	{
		tempNode = ColorsAndShapesList;
		while ((tempNode) && (strcmp("default", tempNode->name)))
		{
			tempNode = tempNode->next;
		}
		if (tempNode)
		{
			return tempNode->shape;
		}
		else
		{
			return DefaultShape;
		}
	}
}

void MakeDownstreamSVGFile(char* name)
{
	CString graphString;
	INTERACTION* tempInteractionNode;
	MOLECULE* listOfNodesToExpand = 0;
	MOLECULE* tempNode;
	int count = 0;
	char fileName[100];

	tempInteractionNode = InteractionsList;
	graphString = "digraph G {";
	graphString += "size=\"7.5,10\";";
	
	// first do the original node
	while (tempInteractionNode)
	{
		if (!strcmp(tempInteractionNode->source, name))
		{
			count++;
			listOfNodesToExpand = AddToEndOfListOfNodesToExpand(tempInteractionNode->target, listOfNodesToExpand);
			graphString = AddThisInteraction(tempInteractionNode, graphString);
		}
		tempInteractionNode = tempInteractionNode->next;
	}	

	if (count == 0)
	{
		graphString += "NoDownstreamEffectors;";
	}

	tempNode = listOfNodesToExpand;

	// do all the child nodes
	while (tempNode)
	{
		tempInteractionNode = InteractionsList;
		while (tempInteractionNode)
		{
			if (!strcmp(tempInteractionNode->source, tempNode->name)) 
			{
				if (NotAlreadyInListToExpand(tempInteractionNode->target, listOfNodesToExpand))
				{
					count++;
					listOfNodesToExpand = AddToEndOfListOfNodesToExpand(tempInteractionNode->target, listOfNodesToExpand);
				}
				graphString = AddThisInteraction(tempInteractionNode, graphString);
			}
			tempInteractionNode = tempInteractionNode->next;
		}
		tempNode = tempNode->next;
	}

	FreeListOfNodesToExpand(listOfNodesToExpand);

	graphString += "}";

	strcpy(fileName, name);

	strcat(fileName, "_ds_map");

	if (count > 15)
	{
		DumpStringToSVG(graphString, fileName, 1, 1);
	}
	else
	{
		DumpStringToSVG(graphString, fileName, 0, 1);
	}

	//store count in the molecule record
	tempNode = GetNodeBasedOnName(name);

	tempNode->numberOfDownstreamEffectors = count;

}

void MakeDownstreamNetFile(char* name)
{
	CString graphString;
	INTERACTION* tempInteractionNode;
	MOLECULE* listOfNodesToExpand = 0;
	MOLECULE* tempNode;
	char fileName[100];
	ifstream connections;
    ofstream graph;
	MOLECULE* tempNode1;
	INTERACTION* tempInteraction;    
	char colorAndShape[100];
	char moleculeTypeIndex;
	
	strcpy(fileName, name);
	strcat(fileName, ".net");

	graph.open(fileName);

	tempInteractionNode = InteractionsList;

	
	// first do the original node
	while (tempInteractionNode)
	{
		if (!strcmp(tempInteractionNode->source, name))
		{
			listOfNodesToExpand = AddToEndOfListOfNodesToExpand(tempInteractionNode->target, listOfNodesToExpand);
		}
		tempInteractionNode = tempInteractionNode->next;
	}	

	tempNode = listOfNodesToExpand;

	// do all the child nodes
	while (tempNode)
	{
		tempInteractionNode = InteractionsList;
		while (tempInteractionNode)
		{
			if (!strcmp(tempInteractionNode->source, tempNode->name)) 
			{
				if (NotAlreadyInListToExpand(tempInteractionNode->target, listOfNodesToExpand))
				{
					listOfNodesToExpand = AddToEndOfListOfNodesToExpand(tempInteractionNode->target, listOfNodesToExpand);
				}
			}
			tempInteractionNode = tempInteractionNode->next;
		}
		tempNode = tempNode->next;
	}


	graph << "*Vertices    " << NumberOfMolecules << endl;

	//store count in the molecule record
	tempNode = MoleculesList;

	while (tempNode)
	{
		moleculeTypeIndex = GetMoleculeTypeIndex(tempNode->moleculeType);

		GetColorAndShape(moleculeTypeIndex, colorAndShape);

		if (TempNodeAlsoInListToExpand(listOfNodesToExpand, tempNode))
		{

			graph << tempNode->number << "  " << "\"" << tempNode->name << "\"" << "ic Red diamond" << endl;
		}
		else
		{
			graph << tempNode->number << "  " << "\"" << tempNode->name << "\"" << " ic Green ellipse" << endl;
		}
		
		tempNode = tempNode->next;
	}


	graph << "*Arcs" << endl;


	tempInteraction = InteractionsList;

	while (tempInteraction)
    { 
	    tempNode = GetNodeBasedOnName(tempInteraction->source);
		tempNode1 = GetNodeBasedOnName(tempInteraction->target);

		if ((TempNodeAlsoInListToExpand(listOfNodesToExpand, tempNode)) && (TempNodeAlsoInListToExpand(listOfNodesToExpand, tempNode)))
		{
			graph << "   " << GetNumberBasedOnString(tempInteraction->source) << "    " << GetNumberBasedOnString(tempInteraction->target) << "    " <<  "1" << endl;
		}
		tempInteraction = tempInteraction->next;
    }
	
	graph.close();

	FreeListOfNodesToExpand(listOfNodesToExpand);

}

bool TempNodeAlsoInListToExpand(MOLECULE* listOfNodesToExpand, MOLECULE* tempNode)
{
	MOLECULE* listToExpandTempNode;

	listToExpandTempNode = listOfNodesToExpand;

	while (listToExpandTempNode)
	{
		if (!strcmp(listToExpandTempNode->name, tempNode->name))
		{
			return 1;
		}
		listToExpandTempNode = listToExpandTempNode->next;
	}

	return 0;

}

void FreeListOfNodesToExpand(MOLECULE* listOfNodesToExpand)
{
	MOLECULE* tempNode;

	tempNode = listOfNodesToExpand;

	while (listOfNodesToExpand)
	{
		listOfNodesToExpand = tempNode->next;
		free(tempNode);
		tempNode = listOfNodesToExpand;
	}

	return;
}

void FreeListToDraw(void)
{
	MOLECULE* tempNode;

	tempNode = ListToDraw;

	while (ListToDraw)
	{
		ListToDraw = tempNode->next;
		free(tempNode);
		tempNode = ListToDraw;
	}

	return;
}

MOLECULE* AddToEndOfListOfNodesToExpand(char* name, MOLECULE* listOfNodesToExpand)
{
	MOLECULE* tempNode;

	tempNode = listOfNodesToExpand;

	if (tempNode == 0)
	{
		tempNode = (MOLECULE*) malloc(sizeof(MOLECULE));
        strcpy(tempNode->name, name);
		tempNode->number = GetNumberBasedOnString(name);
		tempNode->next = 0;
		return tempNode;
	}
	
	while (tempNode->next)
	{
		tempNode = tempNode->next;
	}

	tempNode->next = (MOLECULE*) malloc(sizeof(MOLECULE));
	tempNode = tempNode->next;
    strcpy(tempNode->name, name);
	tempNode->number = GetNumberBasedOnString(name);
	tempNode->next = 0;
	return listOfNodesToExpand;
}

bool NotAlreadyInListToExpand(char* name, MOLECULE* listOfNodesToExpand)
{
	MOLECULE* tempNode;

	tempNode = listOfNodesToExpand;

	while(tempNode)
	{
		if (!strcmp(tempNode->name, name))
		{
			return 0;
		}
		tempNode = tempNode->next;
	}

	return 1;
}


CString AddThisInteraction(INTERACTION* tempInteractionNode, CString inputString)
{
	CString graphString;

	graphString = inputString;

	graphString +=  tempInteractionNode->source;
	graphString += " [style=\"filled\", URL=\"";
	graphString +=	tempInteractionNode->source;
	graphString +=	".htm\"";
		
	graphString += " shape=\"";
	graphString += GetShape(tempInteractionNode->source);
	graphString += "\", color=\"";
	graphString += GetColor(tempInteractionNode->source);
	graphString += "\"];\n";

	graphString +=  tempInteractionNode->target;
	graphString += " [style=\"filled\", URL=\"";
	graphString +=	tempInteractionNode->target;
	graphString +=	".htm\"";
		
	graphString += " shape=\"";
	graphString += GetShape(tempInteractionNode->target);
	graphString += "\", color=\"";
	graphString += GetColor(tempInteractionNode->target);
	graphString += "\"];\n";

	graphString +=  tempInteractionNode->source;
	graphString +=  " -> ";
	graphString +=  tempInteractionNode->target;
			
	if (!strcmp(tempInteractionNode->effect, "+"))
	{
		graphString += " [arrowhead=\"normal\", color=\"darkgreen\"] ";
	}
	else if (!strcmp(tempInteractionNode->effect, "_"))
	{
		graphString += " [arrowhead=\"tee\",arrowsize=\"3.0\", color=\"red1\"] ";
	}
	else if (!strcmp(tempInteractionNode->effect, "0"))
	{
		graphString += " [arrowhead=\"box\",arrowtail=\"box\", color=\"blue1\"] ";
	}
	graphString +=  ";\n";

	return graphString;
}

void MakeDownstreamHTMLFile(char* name)
{
	ofstream out;
	INTERACTION* tempInteractionNode;
	int j;

	j = 1;
	tempInteractionNode = InteractionsList;

	char fileName[1000];

	strcpy(fileName, name);
	
	strcat(fileName, "_ds_map.htm");
	
	out.open(fileName);

	out << "<HTML><BODY>";

	out << "<CENTER><H3>" << name << " Downstream Map</H3></CENTER>" << endl;
	out << "<CENTER>" << "<EMBED SRC=\"" << name << "_ds_map.svg\" width=\"742\" height=\"600\" type=\"image/svg+xml\" /></CENTER>" << endl;
	out << "<BR>";


	out << "</BODY></HTML>" << endl;
}

void CTestSVGDlg::OnButtonViewer() 
{
	if (strcmp(LastViewerCall, "Null"))
	{
		StartViewer(LastViewerCall);
	}
}

void CreateMainWebPage(void)
{
	ofstream out;

	out.open("index.htm");
	
	out << "<HTML><BODY>";
	
	out << "<CENTER>" << "<EMBED SRC=\"" << "network.svg\" width=\"742\" height=\"300\" type=\"image/svg+xml\" /></CENTER>" << endl;

	out << "<BR><A HREF=\"stats.htm\">Network's statistics</A> | <A HREF=\"list.htm\">Index of molecules</A> | <A HREF=\"colors_and_shapes.htm\">Colors and shapes</A> <BR> ";

	out << "</BODY></HTML>";

	out.close();
}

void CreateStatisticalAnalysisWebPage(void)
{
	ofstream out;
	int i;
	float cpl;
	out.open("stats.htm");
	
	out << "<HTML><BODY>";
	
	out << "<B>Number of components: </B>" << NumberOfMolecules << "<BR>";
	out << "<B>Number of interactions: </B>" << NumberOfInteractions << "<BR>";
	out << "<B>Number of references: </B>" << GetNumberOfReferences() << "<BR>";

	if (DoDownstreamMaps)
	{
		out << "<B>Average downstream effectors per component: </B>" << ComputeAvgDownstream() << " which is " << (ComputeAvgDownstream() / NumberOfMolecules * 100) << "% <BR>";
	}
	
	out << "<TABLE><TD>";

	
	out << "<BR><BR><BR><BR><BR><B>Types of molecules:</B><BR>";
	
	CountNumberOfMoleculeTypes();

	out << "Total types of molecules: " << CountOfMoleculeTypes << "<BR>";
	
	for (i = 0; i < CountOfMoleculeTypes; i++)
	{
		out << MoleculeTypesNames[i] << ": " << MoleculeTypesCounts[i] << "<BR>";
	}

	out << "</TD><TD></TD><TD>";

	out << "<B>Types of locations:</B><BR>";

	CountNumberOfLocations();

	out << "Total types of locations: " << CountOfLocations << "<BR>";
	
	for (i = 0; i < CountOfLocations; i++)
	{
		out << LocationsNames[i] << ": " << LocationsCounts[i] << "<BR>";
	}

	out << "<BR><B>Effects:</B><BR>";
	
	CountNumberOfEffects();

	out << "Total types of effects: " << CountOfEffects << "<BR>";
	
	for (i = 0; i < CountOfEffects; i++)
	{
		out << EffectNames[i] << ": " << EffectCounts[i] << "<BR>";
	}

	out << "<BR><B>Types of interactions:</B><BR>";

	CountNumberOfTypeOfInteractions();

	out << "Total types of interactions: " << CountOfTypeOfInteractions << "<BR>";
	
	for (i = 0; i < CountOfTypeOfInteractions; i++)
	{
		out << TypeOfInteractionsNames[i] << ": " << TypeOfInteractionsCounts[i] << "<BR>";
	}

	out << "</TD></TABLE>";

	out << "<BR><B>Connectivity distribution: </B><BR>";

	SetConnectivityDistribution();

	out << "<TABLE><TR>";
	for (i = 0; i < 50; i++)
	{
		out << "<TD>" << i + 1 << "</TD>";
	}
	out << "</TR><TR>";
	
	for (i = 0; i < 50; i++)
	{
		out << "<TD>" << ConnectivityDistributionArray[i] << "</TD>";
	}

	out << "</TR>";

	for (i = 0; i < 50; i++)
	{
		out << "<TD>" << InConnectivityDistributionArray[i] << "</TD>";
	}

	out << "</TR>";

	for (i = 0; i < 50; i++)
	{
		out << "<TD>" << OutConnectivityDistributionArray[i] << "</TD>";
	}

	out << "</TR></TABLE>\n";

	out << "<BR>";
	out << "<B>Average links per node: </B>" << ComputeAvgLinksPerComponent()  << "<BR>";
	if (NumberOfMolecules < 500)
	{
		cpl = ComputeAvgPathLength();
		if (cpl > 0.0)
		{
			out << "<B>Characteristic Path Length: </B>" << cpl << "<BR>";
		}
	}
	out << "<B>Clustering Coefficient: </B>" << ComputeCC() << "<BR>";
	out << "<B>Grid Coefficient: </B>" << ComputeGC() << "<BR>";
	out << "<BR>";

	out << "</BODY></HTML>";

	out.close();
}

void CountUndirectedUniqueCycles(void)
{
	int listSoFar[100];
	int k;
	MOLECULE* tempNode;
	int count = 0;

	ResetDirectedUniqueCycles();

	for (k = 4; k < 13; k++)
	{
		ResetUniqueList();
		

		tempNode = MoleculesList;
	
		while (tempNode)
		{
			listSoFar[0] = tempNode->number;
			ExpandUndirectedUnique(tempNode, tempNode, k, 1, listSoFar);
			tempNode = tempNode->next;
		}
	}
}

void CountDirectedUniqueCycles(void)
{
	int listSoFar[100];
	int k;
	MOLECULE* tempNode;
	int count = 0;

	ResetDirectedUniqueCycles();

	for (k = 9; k < 11; k++)
	{
		ResetUniqueList();
		
		
		tempNode = MoleculesList;
	
		while (tempNode)
		{
			listSoFar[0] = tempNode->number;
			ExpandDirectedUnique(tempNode, tempNode, k, 1, listSoFar);
			tempNode = tempNode->next;
		}
	}
}

void CountUndirectedCycles(void)
{
	int listSoFar[100];
	int k;
	MOLECULE* tempNode;
	int count = 0;

	for (k = 0; k < 100; k++)
	{
		UndirectedCycles[k] = 0;
	}

	for (k = 9; k < 11; k++)
	{
		tempNode = MoleculesList;
	
		while (tempNode)
		{
			listSoFar[0] = tempNode->number;
			Expand(tempNode, tempNode, k, 1, listSoFar);
			tempNode = tempNode->next;
		}
	}

}

void CountDirectedCycles(int size, LPVOID pParam)
{
	int listSoFar[100];
	int k;
	MOLECULE* tempNode;
	int count = 0;

	for (k = 0; k < 100; k++)
	{
		DirectedCycles[k] = 0;
		PositiveFeedbackLoops[k] = 0;
		NegativeFeedbackLoops[k] = 0;
	}

	tempNode = MoleculesList;

	while (tempNode)
	{
		tempNode->appearInFeedbackLoops = 0;
		tempNode = tempNode->next;
	}

	for (k = (size + 1); k < (size + 2); k++)
	{
		tempNode = MoleculesList;
	
		while (tempNode)
		{
			::PostMessage((HWND) pParam, WM_UPDATE_MOTIFS_SEARCH_PROGRESS, 0, 0);
			listSoFar[0] = tempNode->number;
			ExpandDirectOnly(tempNode, tempNode, (size + 1), 1, listSoFar);
			tempNode = tempNode->next;
		}
	}
}

void CountScaffoldCycles(LPVOID pParam)
{
	int listSoFar[100];
	int k;
	MOLECULE* tempNode;
	int count = 0;

	for (k = 0; k < 100; k++)
	{
		ScaffoldCycles[k] = 0;
	}

	tempNode = MoleculesList;

	for (k = 4; k < 5; k++)
	{
		tempNode = MoleculesList;
	
		while (tempNode)
		{
			::PostMessage((HWND) pParam, WM_UPDATE_MOTIFS_SEARCH_PROGRESS, 0, 0);
			listSoFar[0] = tempNode->number;
			ExpandScaffoldOnly(tempNode, tempNode, k, 1, listSoFar);
			tempNode = tempNode->next;
		}
	}
}

void CountBifanCycles(LPVOID pParam)
{
	int listSoFar[100];
	int k;
	MOLECULE* tempNode;
	int count = 0;

	for (k = 0; k < 100; k++)
	{
		BifanCycles[k] = 0;
	}

	tempNode = MoleculesList;

	while (tempNode)
	{
		tempNode->appearInBifans = 0;
		tempNode = tempNode->next;
	}

	tempNode = MoleculesList;

	for (k = 5; k < 6; k++)
	{
		tempNode = MoleculesList;
	
		while (tempNode)
		{
			::PostMessage((HWND) pParam, WM_UPDATE_MOTIFS_SEARCH_PROGRESS, 0, 0);
			listSoFar[0] = tempNode->number;
			ExpandBifanOnly(tempNode, tempNode, k, 1, listSoFar, 0);
			tempNode = tempNode->next;
		}
	}
}

void CountConvergedCycles(int size, LPVOID pParam)
{
	int listSoFar[100];
	int k;
	MOLECULE* tempNode;
	int count = 0;


	for (k = 0; k < 100; k++)
	{
		ConvergedCycles[k] = 0;
		PositiveConvergedCycles[k] = 0;
		Gates[k] = 0;
	}

	tempNode = MoleculesList;

	while (tempNode)
	{
		tempNode->appearInFeedforwardLoops = 0;
		tempNode = tempNode->next;
	}

	for (k = (size + 1); k < (size + 2); k++)
	{
		tempNode = MoleculesList;
	
		while (tempNode)
		{
			::PostMessage((HWND) pParam, WM_UPDATE_MOTIFS_SEARCH_PROGRESS, 0, 0);
			listSoFar[0] = tempNode->number;
			ExpandConvergedOnly(tempNode, tempNode, size + 1, 1, listSoFar, 0);
			tempNode = tempNode->next;
		}
	}

}

void Expand (MOLECULE* sourceNode, MOLECULE* tempNode, int sizeWeLookFor, int howDeep, int* listSoFar)
{
	MOLECULE* localNode;
	int i;

	localNode = tempNode;

	if (howDeep == sizeWeLookFor)
	{
		if (!strcmp(tempNode->name, sourceNode->name))
		{

			UndirectedCycles[sizeWeLookFor]++;
		}

	}
	else if ((howDeep > 1) && (!strcmp(tempNode->name, sourceNode->name)))
	{
		return;
	}
	else
	{
		for (i = 0; i < tempNode->linksCount; i++)
		{	
			localNode = GetNodeBasedOnNumber(tempNode->linksTo[i]);

			if (NotAlreadyInList(listSoFar, howDeep, localNode->number))
			{
				listSoFar[howDeep - 1] = localNode->number;
				Expand(sourceNode, localNode, sizeWeLookFor, howDeep + 1, listSoFar);
			}
		}
	}	
}

void ExpandDirectOnly (MOLECULE* sourceNode, MOLECULE* tempNode, int sizeWeLookFor, int howDeep, int* listSoFar)
{
	MOLECULE* localNode;
	MOLECULE* tempNode2;
	int i;
	int nodeNumber;
	int type = 1;
	int sign = 0;

	localNode = tempNode;

	if (howDeep == sizeWeLookFor)
	{
		if (!strcmp(tempNode->name, sourceNode->name))
		{
			if (IsItNegativeLoop(listSoFar, sizeWeLookFor - 1))
			{
				sign = -1;

				NegativeFeedbackLoops[sizeWeLookFor]++;

				for (i = 0; i < sizeWeLookFor - 1; i++)
				{
					nodeNumber = listSoFar[i];

					tempNode2 = GetNodeBasedOnNumber(nodeNumber);

					tempNode2->appearInFeedbackLoops++;
				}

				if ((sizeWeLookFor - 1) == 3)
				{
					AddToNFBL3Array(GetNodeBasedOnNumber(listSoFar[0])->name, GetNodeBasedOnNumber(listSoFar[1])->name, 
						GetNodeBasedOnNumber(listSoFar[2])->name);

				}	 
				else if ((sizeWeLookFor - 1) == 4)
				{
					AddToNFBL4Array(GetNodeBasedOnNumber(listSoFar[0])->name, GetNodeBasedOnNumber(listSoFar[1])->name, 
						GetNodeBasedOnNumber(listSoFar[2])->name, GetNodeBasedOnNumber(listSoFar[3])->name);
				}
			}
			else
			{
				sign = 1;

				PositiveFeedbackLoops[sizeWeLookFor]++;

				for (i = 0; i < sizeWeLookFor - 1; i++)
				{
					nodeNumber = listSoFar[i];

					tempNode2 = GetNodeBasedOnNumber(nodeNumber);

					tempNode2->appearInFeedbackLoops++;
				}

				if ((sizeWeLookFor - 1) == 3)
				{
					AddToPFBL3Array(GetNodeBasedOnNumber(listSoFar[0])->name, GetNodeBasedOnNumber(listSoFar[1])->name, 
						GetNodeBasedOnNumber(listSoFar[2])->name);

				}	 
				else if ((sizeWeLookFor - 1) == 4)
				{
					AddToPFBL4Array(GetNodeBasedOnNumber(listSoFar[0])->name, GetNodeBasedOnNumber(listSoFar[1])->name, 
						GetNodeBasedOnNumber(listSoFar[2])->name, GetNodeBasedOnNumber(listSoFar[3])->name);
				}
				LoopsFile << endl;
			}
			if ((sizeWeLookFor - 1) == 3)
			{
				AddToFBL3Array(GetNodeBasedOnNumber(listSoFar[0])->name, GetNodeBasedOnNumber(listSoFar[1])->name, 
					GetNodeBasedOnNumber(listSoFar[2])->name);

				Motif3List = AddMotif3(GetNodeBasedOnNumber(listSoFar[0])->name, GetNodeBasedOnNumber(listSoFar[1])->name, 
					GetNodeBasedOnNumber(listSoFar[2])->name, type, sign);
			} 
			else if ((sizeWeLookFor - 1) == 4)
			{
				AddToFBL4Array(GetNodeBasedOnNumber(listSoFar[0])->name, GetNodeBasedOnNumber(listSoFar[1])->name, 
					GetNodeBasedOnNumber(listSoFar[2])->name, GetNodeBasedOnNumber(listSoFar[3])->name);

				Motif4List = AddMotif4(GetNodeBasedOnNumber(listSoFar[0])->name, GetNodeBasedOnNumber(listSoFar[1])->name, 
					GetNodeBasedOnNumber(listSoFar[2])->name, GetNodeBasedOnNumber(listSoFar[3])->name, type, sign);
			}
			else if ((sizeWeLookFor - 1) == 5)
			{
				Motif5List = AddMotif5(GetNodeBasedOnNumber(listSoFar[0])->name, GetNodeBasedOnNumber(listSoFar[1])->name, 
					GetNodeBasedOnNumber(listSoFar[2])->name, GetNodeBasedOnNumber(listSoFar[3])->name, GetNodeBasedOnNumber(listSoFar[4])->name);
			}

			DirectedCycles[sizeWeLookFor]++;
		}

	}
	else if ((howDeep > 1) && (!strcmp(tempNode->name, sourceNode->name)))
	{
		return;
	}
	else
	{
		for (i = 0; i < tempNode->linksCount; i++)
		{	
			localNode = GetNodeBasedOnNumber(tempNode->linksTo[i]);

			if (localNode && (NotAlreadyInList(listSoFar, howDeep, localNode->number) && (DirectionOnlyOK(tempNode, localNode))))
			{
				listSoFar[howDeep - 1] = localNode->number;
				ExpandDirectOnly(sourceNode, localNode, sizeWeLookFor, howDeep + 1, listSoFar);
			}
		}
	}	
}

void ExpandScaffoldOnly (MOLECULE* sourceNode, MOLECULE* tempNode, int sizeWeLookFor, int howDeep, int* listSoFar)
{
	MOLECULE* localNode;
	int i;
	localNode = tempNode;

	if (howDeep == sizeWeLookFor)
	{
		if (!strcmp(tempNode->name, sourceNode->name))
		{
			ScaffoldCycles[sizeWeLookFor]++;

			AddToSCAFFOLDArray(GetNodeBasedOnNumber(listSoFar[0])->name, GetNodeBasedOnNumber(listSoFar[1])->name, 
							GetNodeBasedOnNumber(listSoFar[2])->name);

			Motif3List = AddMotif3(GetNodeBasedOnNumber(listSoFar[0])->name, GetNodeBasedOnNumber(listSoFar[1])->name, 
					GetNodeBasedOnNumber(listSoFar[2])->name, 3, 0);

		}
	}
	else if ((howDeep > 1) && (!strcmp(tempNode->name, sourceNode->name)))
	{
		return;
	}
	else
	{
		for (i = 0; i < tempNode->linksCount; i++)
		{	
			localNode = GetNodeBasedOnNumber(tempNode->linksTo[i]);

			if (localNode && (NotAlreadyInList(listSoFar, howDeep, localNode->number) && (ScaffoldOK(tempNode, localNode))))
			{
				listSoFar[howDeep - 1] = localNode->number;
				ExpandScaffoldOnly(sourceNode, localNode, sizeWeLookFor, howDeep + 1, listSoFar);
			}
		}
	}	
}

void ExpandConvergedOnly (MOLECULE* sourceNode, MOLECULE* tempNode, int sizeWeLookFor, int howDeep, int* listSoFar, int directionFlag)
{
	MOLECULE* localNode;
	MOLECULE* tempNode2;
	int i;
	int nodeNumber;
	int flag;
	int symmetricFlag;
	int sign = 0;

	localNode = tempNode;

	if (howDeep == sizeWeLookFor)
	{
		if (!strcmp(tempNode->name, sourceNode->name))
		{
			if (directionFlag == 2)
			{
				if (IsItGate(listSoFar, sizeWeLookFor - 1))
				{
					sign = -1;
					if (IsItSymmetric(listSoFar, sizeWeLookFor - 1))
					{
						Gates[sizeWeLookFor]++;
						symmetricFlag = 1;
					}
					else
					{
						Gates[sizeWeLookFor]++;
						Gates[sizeWeLookFor]++;
						symmetricFlag = 0;
					}
					
					for (i = 0; i < sizeWeLookFor - 1; i++)
					{
						nodeNumber = listSoFar[i];

						tempNode2 = GetNodeBasedOnNumber(nodeNumber);

						tempNode2->appearInFeedforwardLoops++;
					}

					if ((sizeWeLookFor - 1) == 3)
					{
						AddToNFFL3Array(GetNodeBasedOnNumber(listSoFar[0])->name, GetNodeBasedOnNumber(listSoFar[1])->name, 
							GetNodeBasedOnNumber(listSoFar[2])->name);

					}	 
					else if ((sizeWeLookFor - 1) == 4)
					{
						AddToNFFL4Array(GetNodeBasedOnNumber(listSoFar[0])->name, GetNodeBasedOnNumber(listSoFar[1])->name, 
							GetNodeBasedOnNumber(listSoFar[2])->name, GetNodeBasedOnNumber(listSoFar[3])->name);

					}
				}
				else
				{
					sign = 1;

					if (IsItSymmetric(listSoFar, sizeWeLookFor - 1))
					{
						PositiveConvergedCycles[sizeWeLookFor]++;
						symmetricFlag = 1;
					}
					else
					{
						PositiveConvergedCycles[sizeWeLookFor]++;
						PositiveConvergedCycles[sizeWeLookFor]++;
						symmetricFlag = 0;
					}
					

					for (i = 0; i < sizeWeLookFor - 1; i++)
					{
						nodeNumber = listSoFar[i];

						tempNode2 = GetNodeBasedOnNumber(nodeNumber);

						tempNode2->appearInFeedforwardLoops++;
					}

					if ((sizeWeLookFor - 1) == 3)
					{
						AddToPFFL3Array(GetNodeBasedOnNumber(listSoFar[0])->name, GetNodeBasedOnNumber(listSoFar[1])->name, 
							GetNodeBasedOnNumber(listSoFar[2])->name);

					}	 
					else if ((sizeWeLookFor - 1) == 4)
					{
						AddToPFFL4Array(GetNodeBasedOnNumber(listSoFar[0])->name, GetNodeBasedOnNumber(listSoFar[1])->name, 
							GetNodeBasedOnNumber(listSoFar[2])->name, GetNodeBasedOnNumber(listSoFar[3])->name);
					}
				}

				if ((sizeWeLookFor - 1) == 3)
				{
					AddToFFL3Array(GetNodeBasedOnNumber(listSoFar[0])->name, GetNodeBasedOnNumber(listSoFar[1])->name, 
							GetNodeBasedOnNumber(listSoFar[2])->name);

					Motif3List = AddMotif3(GetNodeBasedOnNumber(listSoFar[0])->name, GetNodeBasedOnNumber(listSoFar[1])->name, 
							GetNodeBasedOnNumber(listSoFar[2])->name, 2, sign);
				} 
				else if ((sizeWeLookFor - 1) == 4)
				{
					AddToFFL4Array(GetNodeBasedOnNumber(listSoFar[0])->name, GetNodeBasedOnNumber(listSoFar[1])->name, 
							GetNodeBasedOnNumber(listSoFar[2])->name, GetNodeBasedOnNumber(listSoFar[3])->name);

					Motif4List = AddMotif4(GetNodeBasedOnNumber(listSoFar[0])->name, GetNodeBasedOnNumber(listSoFar[1])->name, 
							GetNodeBasedOnNumber(listSoFar[2])->name, GetNodeBasedOnNumber(listSoFar[3])->name, 2, sign);
				}
				else if ((sizeWeLookFor - 1) == 5)
				{
					//Motif5List = AddMotif5(GetNodeBasedOnNumber(listSoFar[0])->name, GetNodeBasedOnNumber(listSoFar[1])->name, 
					//GetNodeBasedOnNumber(listSoFar[2])->name, GetNodeBasedOnNumber(listSoFar[3])->name, GetNodeBasedOnNumber(listSoFar[4])->name);
				}

				ConvergedCycles[sizeWeLookFor]++;

				if (!symmetricFlag)
				{
					ConvergedCycles[sizeWeLookFor]++;
				}
			}
		}

	}
	else if ((howDeep > 1) && (!strcmp(tempNode->name, sourceNode->name)))
	{
		return;
	}
	else
	{
		if (tempNode->linksCount > 1)
		{
			for (i = 0; i < tempNode->linksCount; i++)
			{	
				localNode = GetNodeBasedOnNumber(tempNode->linksTo[i]);
				flag  = 0;			
				if ((OppositeDirectionOK(tempNode, localNode)) && (NotAlreadyInList(listSoFar, howDeep, localNode->number)) && (directionFlag == 1) && (howDeep != 1) && (strcmp(localNode->name, sourceNode->name)))
				{
					flag = 2;
				}
				else if ((DirectionOnlyOK(tempNode, localNode)) && (NotAlreadyInList(listSoFar, howDeep, localNode->number)) && (directionFlag == 1))
				{
					flag = 1;
				}	
				else if (NotAlreadyInList(listSoFar, howDeep, localNode->number) && (DirectionOnlyOK(tempNode, localNode)) && (directionFlag == 0))
				{
					flag = 1; 
				}
				else if ((OppositeDirectionOK(tempNode, localNode)) && (NotAlreadyInList(listSoFar, howDeep, localNode->number)) && (directionFlag == 2))
				{
					flag = 2;
				}

				if (flag)
				{
					listSoFar[howDeep] = localNode->number;
					ExpandConvergedOnly(sourceNode, localNode, sizeWeLookFor, howDeep + 1, listSoFar, flag);
				}
			}	
		}
	}	
}

void ExpandBifanOnly (MOLECULE* sourceNode, MOLECULE* tempNode, int sizeWeLookFor, int howDeep, int* listSoFar, int flipFlag)
{
	MOLECULE* localNode;
	MOLECULE* tempNode2;
	int i;
	int nodeNumber;

	localNode = tempNode;

	if (howDeep == sizeWeLookFor)
	{
		if (!strcmp(tempNode->name, sourceNode->name))
		{

			BifanCycles[sizeWeLookFor]++;

			for (i = 0; i < sizeWeLookFor - 1; i++)
			{
				nodeNumber = listSoFar[i];

				tempNode2 = GetNodeBasedOnNumber(nodeNumber);

				tempNode2->appearInBifans++;
			}

			AddToBIFANArray(GetNodeBasedOnNumber(listSoFar[0])->name, GetNodeBasedOnNumber(listSoFar[1])->name, 
							GetNodeBasedOnNumber(listSoFar[2])->name, GetNodeBasedOnNumber(listSoFar[3])->name);

			Motif4List = AddMotif4(GetNodeBasedOnNumber(listSoFar[0])->name, GetNodeBasedOnNumber(listSoFar[1])->name, 
							GetNodeBasedOnNumber(listSoFar[2])->name, GetNodeBasedOnNumber(listSoFar[3])->name, 4, 0);
		}
	}
	else if ((howDeep > 1) && (!strcmp(tempNode->name, sourceNode->name)))
	{
		return;
	}
	else
	{
		for (i = 0; i < tempNode->linksCount; i++)
		{	
			localNode = GetNodeBasedOnNumber(tempNode->linksTo[i]);

			if (((localNode && (NotAlreadyInList(listSoFar, howDeep, localNode->number))) &&
				((flipFlag && (OppositeDirectionOK(tempNode, localNode))) ||
				((!flipFlag) && (DirectionOnlyOK(tempNode, localNode))))) &&
				(!((localNode == sourceNode) && (howDeep + 1 != sizeWeLookFor))))
			{
				listSoFar[howDeep] = localNode->number;
				if (flipFlag)
				{
					ExpandBifanOnly(sourceNode, localNode, sizeWeLookFor, howDeep + 1, listSoFar, 0);
				}
				else
				{
					ExpandBifanOnly(sourceNode, localNode, sizeWeLookFor, howDeep + 1, listSoFar, 1);
				}
			}
		}
	}	
}

void ExpandUndirectedUnique(MOLECULE* sourceNode, MOLECULE* tempNode, int sizeWeLookFor, int howDeep, int* listSoFar)
{
	MOLECULE* localNode;
	int i;
	localNode = tempNode;

	if (howDeep == sizeWeLookFor)
	{
		if (!strcmp(tempNode->name, sourceNode->name))
		{
			AddToUniqueList(tempNode, listSoFar, sizeWeLookFor);
			UniqueUndirectedCycles[sizeWeLookFor]++;
		}

	}
	else if ((howDeep > 1) && (!strcmp(tempNode->name, sourceNode->name)))
	{
		return;
	}
	else
	{
		for (i = 0; i < tempNode->linksCount; i++)
		{	
			localNode = GetNodeBasedOnNumber(tempNode->linksTo[i]);

			if (NotAlreadyInUniqueList(localNode->number))
			{
				listSoFar[howDeep - 1] = localNode->number;
				ExpandUndirectedUnique(sourceNode, localNode, sizeWeLookFor, howDeep + 1, listSoFar);
			}
		}
	}	
}

void ExpandDirectedUnique(MOLECULE* sourceNode, MOLECULE* tempNode, int sizeWeLookFor, int howDeep, int* listSoFar)
{
	MOLECULE* localNode;
	//MOLECULE* testNode;
	//ofstream test;
	localNode = tempNode;
	int i;

	if (howDeep == sizeWeLookFor)
	{
		if (!strcmp(tempNode->name, sourceNode->name))
		{
			AddToUniqueList(tempNode, listSoFar, sizeWeLookFor);
			UniqueDirectedCycles[sizeWeLookFor]++;
			//test.open("loops.txt");
			//for (int i = 0; i < sizeWeLookFor - 1; i++)
			//{/
			//	testNode = GetNodeBasedOnNumber(listSoFar[i]);
			//	test << testNode->name << " ";
			//}
			//test.close();
		}

	}
	else if ((howDeep > 1) && (!strcmp(tempNode->name, sourceNode->name)))
	{
		return;
	}
	else
	{
		for (i = 0; i < tempNode->linksCount; i++)
		{	
			localNode = GetNodeBasedOnNumber(tempNode->linksTo[i]);

			if ((NotAlreadyInList(listSoFar, howDeep, localNode->number)) && (DirectionOK(tempNode, localNode)) && 
				NotAlreadyInUniqueList(localNode->number))
			{
				listSoFar[howDeep - 1] = localNode->number;
				ExpandDirectedUnique(sourceNode, localNode, sizeWeLookFor, howDeep + 1, listSoFar);
			}
		}
	}	
}

void AddToUniqueList(MOLECULE* tempNode, int* listSoFar, int size)
{
	int i;

	for (i = 0; i < size; i++)
	{
		UniqueList[UniqueListCount] = listSoFar[i];
		UniqueListCount++;
	}
}

void ShuffleMoleculesList(void)
{
	/* Sleep(rand() % 6);

	seed = clock();
	srand( (unsigned) seed);
		
	for (i = 0; i < NumberOfMolecule; i++)
	{	
		seed = rand() % 6;
		values[i] = seed;
	} */
}

void ResetUniqueList(void)
{
	int i;
	
	UniqueListCount = 0;

	for (i = 0; i < 5000; i++)
	{
		UniqueList[i] = 0;
	}
}

void ResetUndirectedUniqueCycles(void)
{
	int i;

	for (i = 0; i < 100; i++)
	{
		UniqueUndirectedCycles[i] = 0;
	}
}

void ResetDirectedUniqueCycles(void)
{
	int i;

	for (i = 0; i < 100; i++)
	{
		UniqueDirectedCycles[i] = 0;
	}

}

bool NotAlreadyInUniqueList(int number)
{	
	int i;

	for (i = 0; i < UniqueListCount; i++)
	{
		if (UniqueList[i] == number)
		{
			return 0;
		}
	}
	return 1;
}

int DirectionOK(MOLECULE* sourceNode, MOLECULE* targetNode)
{
	INTERACTION* tempNode;

	tempNode = InteractionsList;

	int found = 0;

	while (tempNode)
	{
		if (
			(
			(!strcmp(tempNode->source, sourceNode->name))
			&& 
			(!strcmp(tempNode->target, targetNode->name)) 
			)
			//&&
			//(strcmp(tempNode->effect, "0"))
			
			|| 
			(
			(!strcmp(tempNode->source, targetNode->name))
			&& 
			(!strcmp(tempNode->target, sourceNode->name)) 
		    &&
			(!strcmp(tempNode->effect, "0")) 
			) 
			
			)

			/*
			(!strcmp(tempNode->source, sourceNode->name))
			&& 
			(!strcmp(tempNode->target, targetNode->name))
			) 
			||
			(
			(!strcmp(tempNode->effect, "0"))
			&&
			(!strcmp(tempNode->target, sourceNode->name))
			&& 
			(!strcmp(tempNode->source, targetNode->name))
			) */
			
		{
			found = 1;
			break;
		}
		tempNode = tempNode->next;
	}

	return found;
}

int DirectionOnlyOK(MOLECULE* sourceNode, MOLECULE* targetNode)
{
	INTERACTION* tempNode;

	tempNode = InteractionsList;

	int found = 0;

	while (tempNode)
	{
		if (
			(
			(!strcmp(tempNode->source, sourceNode->name))
			&& 
			(!strcmp(tempNode->target, targetNode->name)) 
			)
			&&
			(strcmp(tempNode->effect, "0")))

			/*
			(!strcmp(tempNode->source, sourceNode->name))
			&& 
			(!strcmp(tempNode->target, targetNode->name))
			) 
			||
			(
			(!strcmp(tempNode->effect, "0"))
			&&
			(!strcmp(tempNode->target, sourceNode->name))
			&& 
			(!strcmp(tempNode->source, targetNode->name))
			) */
			
		{
			found = 1;
			break;
		}
		tempNode = tempNode->next;
	}

	return found;
}

int IsNegative(MOLECULE* sourceNode, MOLECULE* targetNode)
{
	INTERACTION* tempNode;

	tempNode = InteractionsList;

	int found = 0;

	while (tempNode)
	{
		if (
			(
			(!strcmp(tempNode->source, sourceNode->name))
			&& 
			(!strcmp(tempNode->target, targetNode->name))
			) 
			&& 
			(!strcmp(tempNode->effect, "_")) 
			)
			
		{
			found = 1;
			break;
		}
		tempNode = tempNode->next;
	}

	return found;
}

double ComputeCC(void)
{
	MOLECULE* tempNode;
	MOLECULE* neighborNode;
	double cc;
	double localCc;
	int linksFound;
	int i, j, k;

	tempNode = MoleculesList;
	cc = 0;
	
	
	while (tempNode)
	{
		localCc = 0;
		linksFound = 0;
		for (i = 0; i < tempNode->linksCount; i++)
		{
            neighborNode = GetNodeBasedOnNumber(tempNode->linksTo[i]);
			
			for (k = 0; k < neighborNode->linksCount; k++)
			{
				for (j = 0; j < tempNode->linksCount; j++)
				{
					if (neighborNode->linksTo[k] == tempNode->linksTo[j])
					{
						linksFound++;
					}
				}
			}
			
		}

		if ((tempNode->linksCount * (tempNode->linksCount - 1) / 2) && (linksFound))
		{
			linksFound /= 2;
			cc += linksFound / ((tempNode->linksCount * (tempNode->linksCount - 1.0) / 2.0));
			tempNode->cc = linksFound / ((tempNode->linksCount * (tempNode->linksCount - 1.0) / 2.0));
		}
		else
		{
			tempNode->cc = 0;
		}

		tempNode = tempNode->next;
	}
	
	cc = cc / NumberOfMolecules;
    
    return cc;

}

double ComputeAvgPathLength(void)
{
	MOLECULE* tempNode;
	MOLECULE* tempNode1;
	tempNode = MoleculesList;
	double arrayOfAvgPathLengths[15000];
	int cc = 0;
	int i, j, k;
	double avg;
	ofstream out;

	//Floyd and Warshall's algorithm see
	//http://www.cs.panam.edu/~meng/Course/CS6345/Notes/chpt-5/node10.html
	
	if ((NumberOfMolecules > 5000) || (CountIslands() > 1))
	{
		return 0.0;
	}

	for (i=0; i< NumberOfMolecules; i++)
	{
        for (j=0; j < NumberOfMolecules; j++)
        {
			A[i][j] = 9999999;
		}
	}
	
	for (i=0; i < NumberOfMolecules; i++)
	{
        for (j=0; j < NumberOfMolecules; j++)
        {
			tempNode = GetNodeBasedOnNumber(i+1);
			for (k = 0; k < tempNode->linksCount; k++)
			{
				if (tempNode->linksTo[k] == (j+1))
				{
					A[i][j] = 1;
				}
			}

        }
	}

	for (i=0; i < NumberOfMolecules; i++)
	{
        A[i][i] = 0;              // no self cycle
	}

	
    for (k = 0; k < NumberOfMolecules; k++)
	{
        for (i = 0; i < NumberOfMolecules; i++)
		{
             for (j = 0; j < NumberOfMolecules; j++)
			 {

				if (((A[i][k] + A[k][j]) < A[i][j]) && ((A[i][k] + A[k][j]) > 0))
				{
					A[i][j] = A[i][k] + A[k][j];
				}
			 }
		}
    }

	// compute averages
	for (i=0; i < NumberOfMolecules; i++)
	{
		avg = 0;
        for (j=0; j < NumberOfMolecules; j++)
        {
			tempNode = GetNodeBasedOnNumber(i+1);
			tempNode1 = GetNodeBasedOnNumber(j+1);
			tempNode->allPathLengths[j + 1] = A[i][j];
			tempNode1->allPathLengths[i + 1] = A[i][j];
			avg += A[i][j];	 
		}
		arrayOfAvgPathLengths[i] = avg / (NumberOfMolecules - 1);

		// store it in the molecules list
		tempNode = GetNodeBasedOnNumber(i+1);
		tempNode->avgPathLength = arrayOfAvgPathLengths[i];
		
	}

	avg = 0;

	for (i=0; i < NumberOfMolecules; i++)
	{
		avg += arrayOfAvgPathLengths[i];
	}

	avg /= (NumberOfMolecules - 1);

	return avg;
}

double ComputeAvgLinksPerComponent(void)
{
	MOLECULE* tempNode;
	tempNode = MoleculesList;
	double total = 0;
	int count = 0;
	tempNode = MoleculesList;

	while (tempNode)
	{
		count++;
		total += tempNode->linksCount;
		tempNode = tempNode->next;
	}

	total /= count;
	return total;
}

MOLECULE* GetNodeBasedOnNumber(int i)
{
	MOLECULE* tempNode;

	/* look for a match or loop all the way to the end */
    tempNode = MoleculesList;

    /* loop until a match was found or the end */
    while ((tempNode->next != 0) && (tempNode->number != i))
    {
	    tempNode = tempNode->next;
    }

	if (tempNode->number == i)
	{
		return tempNode;
	}
	else
	{
		return 0;
	}
}
MOLECULE* GetNodeBasedOnName(char* name)
{
	MOLECULE* tempNode;

	/* look for a match or loop all the way to the end */
    tempNode = MoleculesList;

    /* loop until a match was found or the end */
    while ((tempNode->next != 0) && (strcmp(tempNode->name, name)))
    {
	    tempNode = tempNode->next;
    }

	if (!(strcmp(tempNode->name, name)))
	{
		return tempNode;
	}
	else
	{
		return 0;
	}
}

void CreateIndexPage(void)
{
	ofstream out;
	MOLECULE* tempNode;

	//SortMoleculeList();

	tempNode = MoleculesList;

	out.open("list.htm");

	out << "<HTML><BODY><TABLE>";

	out << "<TR><TD><B>Name</B></TD><TD><B>Type</B></TD><TD><B>Location</B></TD><TD><B>Links</B></TD><TD><B>In Links</B></TD><TD><B>Out Links</B></TD><TD><B>Positive Links</B></TD><TD><B>Negative Links</B></TD><TD><B>Positive In Links</B></TD><TD><B>Negative In Links</B></TD><TD><B>Positive Out Links</B></TD><TD><B>Negative Out Links</B></TD><TD><B>Neutral Links</B></TD><TD><B>CC</B></TD>";
	
	if (DoDownstreamMaps)
	{
		out << "<TD><B>Downstream Effectors</B></TD></TR>" << endl;
	}
	else
	{
		out << "</TR>" << endl;
	}
	
	while (tempNode)
	{

		out << "<TR><TD><A HREF=\"" << tempNode->name << ".htm\">" << tempNode->name << "</A></TD><TD>" << tempNode->moleculeType;
		out << "</TD><TD>" << tempNode->location << "</TD><TD>" << tempNode->linksCount << "</TD><TD>" << tempNode->inLinksCount << "</TD><TD>" << tempNode->outLinksCount << "</TD><TD>" << tempNode->positiveLinksCount << "</TD><TD>" << tempNode->negativeLinksCount << "</TD><TD>" << tempNode->positiveInLinksCount << "</TD><TD>" << tempNode->negativeInLinksCount << "</TD><TD>" << tempNode->positiveOutLinksCount << "</TD><TD>" << tempNode->negativeOutLinksCount << "</TD><TD>" << tempNode->neutralLinksCount << "</TD><TD>" << tempNode->cc << "</TD>";
		
		if (DoDownstreamMaps)
		{
			out << "</TD><TD>" << tempNode->numberOfDownstreamEffectors << "</TD></TR>" << endl;
		}
		else
		{
			out << "</TR>" << endl;
		}
		tempNode = tempNode->next;
	}

	out << "</TABLE></BODY></HTML>";

	out.close();

}

void SortMoleculeList (void)
{
	MOLECULE* tempNode1;
	MOLECULE* tempNode2;
	MOLECULE* newList = NULL;
	CString savedName;
	CString nextName;

	while (MoleculesList)
	{
		tempNode1 = MoleculesList;
		savedName = tempNode1->name;
		savedName.MakeUpper();
		tempNode2 = tempNode1;

		tempNode1 = tempNode1->next;

		while (tempNode1)
		{
			nextName = tempNode1->name;
			nextName.MakeUpper();
			if (nextName.Compare(savedName) < 0)
			{
				savedName = nextName;
				tempNode2 = tempNode1;
			}
			tempNode1 = tempNode1->next;
		}
		MoleculesList = RemoveFromList(tempNode2);
		tempNode2->next = 0;
		newList = AddToNewList(newList, tempNode2);
	}
	MoleculesList = newList;
}

void SortMoleculeListBasedOnConnectivity (void)
{
	MOLECULE* tempNode1;
	MOLECULE* tempNode2;
	MOLECULE* newList = NULL;
	int saved;
	int next;

	while (MoleculesList)
	{
		tempNode1 = MoleculesList;
		saved = tempNode1->linksCount;
		tempNode2 = tempNode1;

		tempNode1 = tempNode1->next;

		while (tempNode1)
		{
			next = tempNode1->linksCount;
			if (next < saved)
			{
				saved = next;
				tempNode2 = tempNode1;
			}
			tempNode1 = tempNode1->next;
		}
		MoleculesList = RemoveFromList(tempNode2);
		tempNode2->next = 0;
		newList = AddToNewList(newList, tempNode2);
	}
	MoleculesList = newList;
}

void SortMoleculeListBasedOnMotifs (void)
{
	MOLECULE* tempNode1;
	MOLECULE* tempNode2;
	MOLECULE* newList = NULL;
	int saved;
	int next;

	while (MoleculesList)
	{
		tempNode1 = MoleculesList;
		saved = (int) tempNode1->appearInTotal;
		tempNode2 = tempNode1;

		tempNode1 = tempNode1->next;

		while (tempNode1)
		{
			next = (int) tempNode1->appearInTotal;
			if (next > saved)
			{
				saved = next;
				tempNode2 = tempNode1;
			}
			tempNode1 = tempNode1->next;
		}
		MoleculesList = RemoveFromList(tempNode2);
		tempNode2->next = 0;
		newList = AddToNewList(newList, tempNode2);
	}
	MoleculesList = newList;
}

void SortMoleculeListBasedOnMachines (void)
{
	MOLECULE* tempNode1;
	MOLECULE* tempNode2;
	MOLECULE* newList = NULL;
	int saved;
	int next;

	while (MoleculesList)
	{
		tempNode1 = MoleculesList;
		saved = tempNode1->machine;
		tempNode2 = tempNode1;

		tempNode1 = tempNode1->next;

		while (tempNode1)
		{
			next = tempNode1->machine;
			if (next < saved)
			{
				saved = next;
				tempNode2 = tempNode1;
			}
			tempNode1 = tempNode1->next;
		}
		MoleculesList = RemoveFromList(tempNode2);
		tempNode2->next = 0;
		newList = AddToNewList(newList, tempNode2);
	}
	MoleculesList = newList;
}

void SortMotif3List (void)
{
	MOTIF3* tempNode1;
	MOTIF3* tempNode2;
	MOTIF3* newList = NULL;
	int savedCount = 0;

	while (Motif3List)
	{
		tempNode1 = Motif3List;
		tempNode2 = tempNode1;
		savedCount = tempNode1->count;
		tempNode1 = tempNode1->next;

		while (tempNode1)
		{
			if (savedCount < tempNode1->count)
			{
				savedCount = tempNode1->count;
				tempNode2 = tempNode1;
			}
			tempNode1 = tempNode1->next;
		}
		Motif3List = RemoveFromMotif3List(tempNode2);
		tempNode2->next = 0;
		newList = AddToNewMotif3List(newList, tempNode2);
	}
	Motif3List = newList;
}

void SortMotif4List (void)
{
	MOTIF4* tempNode1;
	MOTIF4* tempNode2;
	MOTIF4* newList = NULL;
	int savedCount = 0;

	while (Motif4List)
	{
		tempNode1 = Motif4List;
		tempNode2 = tempNode1;
		savedCount = tempNode1->count;
		tempNode1 = tempNode1->next;

		while (tempNode1)
		{
			if (savedCount < tempNode1->count)
			{
				savedCount = tempNode1->count;
				tempNode2 = tempNode1;
			}
			tempNode1 = tempNode1->next;
		}
		Motif4List = RemoveFromMotif4List(tempNode2);
		tempNode2->next = 0;
		newList = AddToNewMotif4List(newList, tempNode2);
	}
	Motif4List = newList;
}

void SortMotif5List (void)
{
	MOTIF5* tempNode1;
	MOTIF5* tempNode2;
	MOTIF5* newList = NULL;
	int savedCount = 0;

	while (Motif5List)
	{
		tempNode1 = Motif5List;
		tempNode2 = tempNode1;
		savedCount = tempNode1->count;
		tempNode1 = tempNode1->next;

		while (tempNode1)
		{
			if (savedCount < tempNode1->count)
			{
				savedCount = tempNode1->count;
				tempNode2 = tempNode1;
			}
			tempNode1 = tempNode1->next;
		}
		Motif5List = RemoveFromMotif5List(tempNode2);
		tempNode2->next = 0;
		newList = AddToNewMotif5List(newList, tempNode2);
	}
	Motif5List = newList;
}

MOLECULE* RemoveFromList(MOLECULE* tempNode1)
{
	MOLECULE* tempNode;
	MOLECULE* previous;

	if (tempNode1 == MoleculesList)
	{
		MoleculesList = tempNode1->next;
	}
	else
	{	
		tempNode = MoleculesList;
		while (strcmp(tempNode->name, tempNode1->name))
		{
			previous = tempNode;
			tempNode = tempNode->next;
		}
		previous->next = tempNode->next;
		
	}
	return MoleculesList;
}

MOTIF3* RemoveFromMotif3List(MOTIF3* tempNode1)
{
	MOTIF3* tempNode;
	MOTIF3* previous;

	if (tempNode1 == Motif3List)
	{
		Motif3List = tempNode1->next;
	}
	else
	{	
		tempNode = Motif3List;
		while ((strcmp(tempNode->name1, tempNode1->name1)) ||
				(strcmp(tempNode->name2, tempNode1->name2)) ||
				(strcmp(tempNode->name3, tempNode1->name3)) ||
				(strcmp(tempNode->effect1, tempNode1->effect1)) ||
				(strcmp(tempNode->effect2, tempNode1->effect2)) ||
				(strcmp(tempNode->effect3, tempNode1->effect3)) ||
				(tempNode->direction1 != tempNode1->direction1) ||
				(tempNode->direction2 != tempNode1->direction2) ||
				(tempNode->direction3 != tempNode1->direction3) ||
				(strcmp(tempNode->typeOfInteraction1, tempNode1->typeOfInteraction1)) ||
				(strcmp(tempNode->typeOfInteraction2, tempNode1->typeOfInteraction2)) ||
				(strcmp(tempNode->typeOfInteraction3, tempNode1->typeOfInteraction3))
				)
		{
			previous = tempNode;
			tempNode = tempNode->next;
		}
		previous->next = tempNode->next;
		
	}
	return Motif3List;
}

MOTIF4* RemoveFromMotif4List(MOTIF4* tempNode1)
{
	MOTIF4* tempNode;
	MOTIF4* previous;

	if (tempNode1 == Motif4List)
	{
		Motif4List = tempNode1->next;
	}
	else
	{	
		tempNode = Motif4List;
		while ((strcmp(tempNode->name1, tempNode1->name1)) ||
				(strcmp(tempNode->name2, tempNode1->name2)) ||
				(strcmp(tempNode->name3, tempNode1->name3)) ||
				(strcmp(tempNode->name4, tempNode1->name4)) ||
				(strcmp(tempNode->effect1, tempNode1->effect1)) ||
				(strcmp(tempNode->effect2, tempNode1->effect2)) ||
				(strcmp(tempNode->effect3, tempNode1->effect3)) ||
				(strcmp(tempNode->effect4, tempNode1->effect4)) ||
				(tempNode->direction1 != tempNode1->direction1) ||
				(tempNode->direction2 != tempNode1->direction2) ||
				(tempNode->direction3 != tempNode1->direction3) ||
				(tempNode->direction4 != tempNode1->direction4) ||
				(strcmp(tempNode->typeOfInteraction1, tempNode1->typeOfInteraction1)) ||
				(strcmp(tempNode->typeOfInteraction2, tempNode1->typeOfInteraction2)) ||
				(strcmp(tempNode->typeOfInteraction3, tempNode1->typeOfInteraction3)) ||
				(strcmp(tempNode->typeOfInteraction4, tempNode1->typeOfInteraction4))
				)
		{
			previous = tempNode;
			tempNode = tempNode->next;
		}
		previous->next = tempNode->next;
		
	}
	return Motif4List;
}

MOTIF5* RemoveFromMotif5List(MOTIF5* tempNode1)
{
	MOTIF5* tempNode;
	MOTIF5* previous;

	if (tempNode1 == Motif5List)
	{
		Motif5List = tempNode1->next;
	}
	else
	{	
		tempNode = Motif5List;
		while ((strcmp(tempNode->name1, tempNode1->name1)) ||
				(strcmp(tempNode->name2, tempNode1->name2)) ||
				(strcmp(tempNode->name3, tempNode1->name3)) ||
				(strcmp(tempNode->name4, tempNode1->name4)) ||
				(strcmp(tempNode->name5, tempNode1->name5)) ||
				(strcmp(tempNode->effect1, tempNode1->effect1)) ||
				(strcmp(tempNode->effect2, tempNode1->effect2)) ||
				(strcmp(tempNode->effect3, tempNode1->effect3)) ||
				(strcmp(tempNode->effect4, tempNode1->effect4)) ||
				(strcmp(tempNode->effect5, tempNode1->effect5)) ||
				(tempNode->direction1 != tempNode1->direction1) ||
				(tempNode->direction2 != tempNode1->direction2) ||
				(tempNode->direction3 != tempNode1->direction3) ||
				(tempNode->direction4 != tempNode1->direction4) ||
				(tempNode->direction5 != tempNode1->direction5) ||
				(strcmp(tempNode->typeOfInteraction1, tempNode1->typeOfInteraction1)) ||
				(strcmp(tempNode->typeOfInteraction2, tempNode1->typeOfInteraction2)) ||
				(strcmp(tempNode->typeOfInteraction3, tempNode1->typeOfInteraction3)) ||
				(strcmp(tempNode->typeOfInteraction4, tempNode1->typeOfInteraction4)) ||
				(strcmp(tempNode->typeOfInteraction5, tempNode1->typeOfInteraction5))
				)
		{
			previous = tempNode;
			tempNode = tempNode->next;
		}
		previous->next = tempNode->next;
		
	}
	return Motif5List;
}

MOLECULE* AddToNewList(MOLECULE*  newList, MOLECULE* tempNode1)
{
	MOLECULE* tempNode;

	if (newList == NULL)
	{
		newList = tempNode1;
	}
	else
	{
		tempNode = newList;

		while (tempNode->next)
		{
			tempNode = tempNode->next;
		}
		tempNode->next = tempNode1;
	}
	return newList;
}

MOTIF3* AddToNewMotif3List(MOTIF3*  newList, MOTIF3* tempNode1)
{
	MOTIF3* tempNode;

	if (newList == NULL)
	{
		newList = tempNode1;
	}
	else
	{
		tempNode = newList;

		while (tempNode->next)
		{
			tempNode = tempNode->next;
		}
		tempNode->next = tempNode1;
	}
	return newList;
}

MOTIF4* AddToNewMotif4List(MOTIF4*  newList, MOTIF4* tempNode1)
{
	MOTIF4* tempNode;

	if (newList == NULL)
	{
		newList = tempNode1;
	}
	else
	{
		tempNode = newList;

		while (tempNode->next)
		{
			tempNode = tempNode->next;
		}
		tempNode->next = tempNode1;
	}
	return newList;
}

MOTIF5* AddToNewMotif5List(MOTIF5*  newList, MOTIF5* tempNode1)
{
	MOTIF5* tempNode;

	if (newList == NULL)
	{
		newList = tempNode1;
	}
	else
	{
		tempNode = newList;

		while (tempNode->next)
		{
			tempNode = tempNode->next;
		}
		tempNode->next = tempNode1;
	}
	return newList;
}

void CTestSVGDlg::OnButtonSaveAs() 
{
    
	CFileDialog myDialog(FALSE, NULL, "*.sig", OFN_OVERWRITEPROMPT, NULL, NULL );

	myDialog.DoModal();
    
    //LoadNetwork(myDialog.m_ofn.lpstrFile);

	DumpNetwork(myDialog.m_ofn.lpstrFile);

	MessageBox("Done!", "Save as..", MB_OK | MB_ICONINFORMATION);
}

void CTestSVGDlg::OnButton2() 
{
	
}


void CreateColorsAndShape(void)
{
	COLORS_AND_SHAPES* tempNode;
	CString graphString;
	ofstream out;
	
	graphString = "digraph G {";
	
	graphString += "rankdir=LR;\n";
	graphString += "size=\"7.5,20\";\n";
	
	tempNode = ColorsAndShapesList;

	while (tempNode)
	{
		
		graphString +=  tempNode->name;
		graphString += " [style=\"filled\", ";
		graphString += " shape=\"";
		graphString += tempNode->shape;
		graphString += "\", color=\"";
		graphString += tempNode->color;
		graphString += "\"];\n";
		tempNode = tempNode->next;		
	}

	tempNode = ColorsAndShapesList;

	graphString += "};";

	out.open("colors_and_shapes.htm");

	out << "<HTML><BODY><CENTER><EMBED SRC=\"colors_and_shapes.svg\" width=\"742\" height=\"2000\" type=\"image/svg+xml\" /></CENTER></BODY></HTML>";

	//out << graphString;

	out.close();

	DumpStringToSVG(graphString, "colors_and_shapes", 0, 0);

	return;	
}

void CountNumberOfEffects(void)
{
	INTERACTION* tempNode;
	int alreadyThere;
	int i;


	CountOfEffects = 1;
	tempNode = InteractionsList;

	if (!tempNode)
	{
		return;
	}

	EffectNames[0] = (char*) malloc(200);
	EffectCounts[0] = 1;

	strcpy(EffectNames[0], tempNode->effect);

	tempNode = tempNode->next;

	while (tempNode)
	{
		alreadyThere = 0;
		for (i = 0; i < CountOfEffects; i++)
		{
			if (!strcmp(tempNode->effect, EffectNames[i]))
			{
				alreadyThere = 1;
				EffectCounts[i]++;
			}
		}
		if (!alreadyThere)
		{
			EffectNames[CountOfEffects] = (char*) malloc(200);
			strcpy(EffectNames[CountOfEffects], tempNode->effect);
			EffectCounts[CountOfEffects] = 1;
			CountOfEffects++;
		}
		tempNode = tempNode->next;
	}
}

void CountNumberOfMoleculeTypes(void)
{
	MOLECULE* tempNode;
	int alreadyThere;
	int i;


	CountOfMoleculeTypes = 1;
	tempNode = MoleculesList;
	MoleculeTypesNames[0] = (char*) malloc(200);
	MoleculeTypesCounts[0] = 1;

	strcpy(MoleculeTypesNames[0], tempNode->moleculeType);

	tempNode = tempNode->next;

	while (tempNode)
	{
		alreadyThere = 0;
		for (i = 0; i < CountOfMoleculeTypes; i++)
		{
			if (!strcmp(tempNode->moleculeType, MoleculeTypesNames[i]))
			{
				alreadyThere = 1;
				MoleculeTypesCounts[i]++;
			}
		}
		if (!alreadyThere)
		{
			MoleculeTypesNames[CountOfMoleculeTypes] = (char*) malloc(200);
			strcpy(MoleculeTypesNames[CountOfMoleculeTypes], tempNode->moleculeType);
			MoleculeTypesCounts[CountOfMoleculeTypes] = 1;
			CountOfMoleculeTypes++;
		}
		tempNode = tempNode->next;
	}
}

void CountNumberOfLocations(void)
{
	MOLECULE* tempNode;
	int alreadyThere;
	int i;


	CountOfLocations = 1;
	tempNode = MoleculesList;
	LocationsNames[0] = (char*) malloc(200);
	LocationsCounts[0] = 1;

	strcpy(LocationsNames[0], tempNode->location);

	tempNode = tempNode->next;

	while (tempNode)
	{
		alreadyThere = 0;
		for (i = 0; i < CountOfLocations; i++)
		{
			if (!strcmp(tempNode->location, LocationsNames[i]))
			{
				alreadyThere = 1;
				LocationsCounts[i]++;
			}
		}
		if (!alreadyThere)
		{
			LocationsNames[CountOfLocations] = (char*) malloc(200);
			strcpy(LocationsNames[CountOfLocations], tempNode->location);
			LocationsCounts[CountOfLocations] = 1;
			CountOfLocations++;
		}
		tempNode = tempNode->next;
	}
}

void CountNumberOfTypeOfInteractions(void)
{
	INTERACTION* tempNode;
	int alreadyThere;
	int i;


	CountOfTypeOfInteractions = 1;
	tempNode = InteractionsList;
	TypeOfInteractionsNames[0] = (char*) malloc(200);
	TypeOfInteractionsCounts[0] = 1;

	strcpy(TypeOfInteractionsNames[0], tempNode->typeOfInteraction);

	tempNode = tempNode->next;

	while (tempNode)
	{
		alreadyThere = 0;
		for (i = 0; i < CountOfTypeOfInteractions; i++)
		{
			if (!strcmp(tempNode->typeOfInteraction, TypeOfInteractionsNames[i]))
			{
				alreadyThere = 1;
				TypeOfInteractionsCounts[i]++;
			}
		}
		if (!alreadyThere)
		{
			TypeOfInteractionsNames[CountOfTypeOfInteractions] = (char*) malloc(200);
			strcpy(TypeOfInteractionsNames[CountOfTypeOfInteractions], tempNode->typeOfInteraction);
			TypeOfInteractionsCounts[CountOfTypeOfInteractions] = 1;
			CountOfTypeOfInteractions++;
		}
		tempNode = tempNode->next;
	}
}

void SetConnectivityDistribution(void)
{
	int i;

	for (i = 0; i < 30; i++)
	{
		ConnectivityDistributionArray[i] = 0;
		InConnectivityDistributionArray[i] = 0;
		OutConnectivityDistributionArray[i] = 0;
	}

	MOLECULE* tempNode;

	tempNode = MoleculesList;

	while (tempNode)
	{
		ConnectivityDistributionArray[tempNode->linksCount - 1]++;
		InConnectivityDistributionArray[tempNode->inLinksCount - 1]++;
		OutConnectivityDistributionArray[tempNode->outLinksCount - 1]++;
		tempNode = tempNode->next;
	}
}

double ComputeAvgDownstream(void)
{
	MOLECULE* tempNode;
	double avg;
	

	tempNode = MoleculesList;
	avg = 0;
	
	
	while (tempNode)
	{
		avg += tempNode->numberOfDownstreamEffectors;

		tempNode = tempNode->next;
	}
	
	avg = avg / NumberOfMolecules;
    
    return avg;

}

void CTestSVGDlg::OnButtonLoadTwoColumn() 
{
	ifstream inputFile;
    int ret;

	CFileDialog myDialog(TRUE, NULL, "*.txt", OFN_OVERWRITEPROMPT, NULL, NULL );

	ret = myDialog.DoModal();

	if (ret == IDCANCEL)
	{
		return;
	}
    
	FreeNetwork();

    ret = LoadTwoColumnNetwork(myDialog.m_ofn.lpstrFile);
	
	if (ret == 0)
	{
		MessageBox("The network was loaded successfully!", "Loading the network", MB_OK | MB_ICONINFORMATION);
	}
	else if (ret == -1)
	{
		MessageBox("Failed to load network, bad file name!", "Error!", MB_OK | MB_ICONINFORMATION);
		return;
	}
	else if (ret == -2)
	{
		MessageBox("The network was loaded successfully!\nThe colors and shapes file (colors_and_shapes.txt) is empty or missing!\nPut this file in the same directory as the *.sig file.", "Loading the network", MB_OK | MB_ICONINFORMATION);
	}
	CButton* pButtonWebSite = (CButton*) GetDlgItem(IDC_BUTTON_CREATE_WEB_SITE);
	pButtonWebSite->EnableWindow(1);

	CButton* pButtonSaveAs = (CButton*) GetDlgItem(IDC_BUTTON_SAVE_AS);
	pButtonSaveAs->EnableWindow(1);

	CButton* myButton;

	myButton = (CButton*) GetDlgItem(IDC_BUTTON_MOTIFS_INPUT);
	myButton->EnableWindow(1);

	myButton = (CButton*) GetDlgItem(IDC_BUTTON_VALIDATE);
	myButton->EnableWindow(1);

	myButton = (CButton*) GetDlgItem(IDC_BUTTON15);
	myButton->EnableWindow(1);

	myButton = (CButton*) GetDlgItem(IDC_BUTTON_NET);
	myButton->EnableWindow(1);

	myButton = (CButton*) GetDlgItem(IDC_BUTTON19);
	myButton->EnableWindow(1);

	myButton = (CButton*) GetDlgItem(IDC_BUTTON_CREATE_AND_DRAW_PATHWAYS);
	myButton->EnableWindow(1);

	myButton = (CButton*) GetDlgItem(IDC_BUTTON_GENERATE_PATHWAY);
	myButton->EnableWindow(1);

	myButton = (CButton*) GetDlgItem(IDC_BUTTON_LOAD_TWO_COLUMN);
	myButton->EnableWindow(1);

	myButton = (CButton*) GetDlgItem(IDC_BUTTON_MOTIFS);
	myButton->EnableWindow(1);

	inputFile.close();

	CountInAndOutLinks();

    return;
	
}

int NotAlreadyInList(int* listSoFar, int howDeep, int number)
{
	int i;
	for (i = 1; i < howDeep - 1; i++)
	{
		if (listSoFar[i] == number)
		{
			return 0;
		}
	}
	return 1;
}

void ComputeBestLocationsForVisio(void)
{
	MOLECULE* tempNode;
	//MOLECULE* tempNode1;
	//double tempTotalDistance;
	//double ifSwappedTotalDistance;
	tempNode = MoleculesList;
	//int i;

	// set up initial locations
	while (tempNode)
	{
		GetXLocation(tempNode->location);
		tempNode->bestXLocation = XLocationNumber;
		GetYLocation(tempNode->location);
		tempNode->bestYLocation = YLocationNumber;
			
		tempNode = tempNode->next;		
	}

/* needs work
	for (i = 0; i < 10; i++)
	{
		tempNode1 = MoleculesList;

		while (tempNode1)
		{
			tempNode = MoleculesList;

			tempTotalDistance = ComputeDistanceToNeighbors(tempNode1);

			while (tempNode)
			{
				if (!strcmp(tempNode->location, tempNode1->location))
				{
					ifSwappedTotalDistance = ComputeIfSwappedTotalDistance(tempNode1, tempNode);
				
					if (ifSwappedTotalDistance < tempTotalDistance)
					{
						tempTotalDistance = ifSwappedTotalDistance;

						SwapBestXandY(tempNode1, tempNode);
					}
				}			
				tempNode = tempNode->next;		
			}
			tempNode1 = tempNode1->next;		
		}
	}
*/
}


double ComputeDistanceToNeighbors(MOLECULE* node)
{
	int i;
	double total = 0;
	MOLECULE* tempNode;

	for (i = 0; i < node->linksCount; i++)
	{
		tempNode = GetNodeBasedOnNumber(node->linksTo[i]);

		total += sqrt(
				((node->bestXLocation - tempNode->bestXLocation) * (node->bestXLocation - tempNode->bestXLocation))
				+
				((node->bestYLocation - tempNode->bestYLocation) * (node->bestYLocation - tempNode->bestYLocation))
				);
	}

	total = total / node->linksCount;

	return total;
}

double ComputeIfSwappedTotalDistance(MOLECULE* origNode, MOLECULE* newNode)
{
	int i;
	double total = 0;
	MOLECULE* tempNode;

	for (i = 0; i < origNode->linksCount; i++)
	{
		tempNode = GetNodeBasedOnNumber(origNode->linksTo[i]);

		total += sqrt(
				((newNode->bestXLocation - tempNode->bestXLocation) * (newNode->bestXLocation - tempNode->bestXLocation))
				+
				((newNode->bestYLocation - tempNode->bestYLocation) * (newNode->bestYLocation - tempNode->bestYLocation))
				);
	}

	total = total / origNode->linksCount;

	return total;
}

void SwapBestXandY(MOLECULE* origNode, MOLECULE* newNode)
{
	double tempX;
	double tempY;

	tempX = origNode->bestXLocation;
	tempY = origNode->bestYLocation;

	origNode->bestXLocation = newNode->bestXLocation;
	origNode->bestYLocation = newNode->bestYLocation;

	newNode->bestXLocation = tempX;
	newNode->bestYLocation = tempY;
}

void MakeTextForVisio(void)
{
	INTERACTION* tempInteractionNode;
	MOLECULE* tempNode;
	ofstream out;

	out.open("visio_input.txt");

	int i = 1;

	//out << "Template, Basic Flowchart.vst\n";
	//out << "Master,,\"Process\",\"Basic Flowchart Shapes.vss\"\n";
	//out << "Master,,\"Decision\",\"Basic Flowchart Shapes.vss\"\n";
	//out << "Master,,\"Document\",\"Basic Flowchart Shapes.vss\"\n";
	//out << "Master,,\"Data\",\"Basic Flowchart Shapes.vss\"\n";
	//out << "Master,,\"Preparation\",\"Basic Flowchart Shapes.vss\"\n";
	//out << "Master,,\"Display\",\"Basic Flowchart Shapes.vss\"\n";
	//out << "Master,,\"Data\",\"Basic Flowchart Shapes.vss\"\n";
	//out << "Master,,\"Ligand\",\"Basic Flowchart Shapes.vss\"\n";
	//out << "Master,,\"Adhesion\",\"Basic Flowchart Shapes.vss\"\n";
	//out << "Master,,\"Cyclase\",\"Basic Flowchart Shapes.vss\"\n";
	//out << "Master,,\"Protease\",\"Basic Flowchart Shapes.vss\"\n";
	//out << "Master,,\"TF\",\"Basic Flowchart Shapes.vss\"\n";
	//out << "Master,,\"Ubiquitinase\",\"Basic Flowchart Shapes.vss\"\n";
	//out << "Master,,\"G_protein\",\"Basic Flowchart Shapes.vss\"\n";

	out << "Template, Basic Flowchart.vst\n";
	out << "Master,,\"Receptor\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Channel\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Cytoskeleton\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Protease\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Adhesion\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Activator\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"GEF\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Kinase\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Adapter\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Lipid\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"TF\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Ribosome\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"G_protein\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Phosphatase\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Messenger\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Cyclase\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Phospholipase\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"RNA\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Bcl2Family\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"PDE\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Adapter\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Synthase\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Ubiquitinase\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"GAP\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Ion\",\"Cell Signaling.vss\"\n";

	out << "Master,,\"Positive connector\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Negative connector\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"No effect connector\",\"Cell Signaling.vss\"\n";

	tempNode = MoleculesList;
	
	
	while (tempNode)
	{
		out << "Shape,\"";
		out << tempNode->name;
		out << "\",\"";
		out << GetVisioShape(tempNode->moleculeType);
		out << "\",\"";
		out << tempNode->name;
		out << "\",";
		//GetXLocation(tempNode->location);
		//out << XLocation;
		out << tempNode->bestXLocation;
		out << ",";
		//GetYLocation(tempNode->location);
		//out << YLocation;
		out << tempNode->bestYLocation;
		out << ",,,,,,\n";
			
		tempNode = tempNode->next;		
	}

	i = 1;
	tempInteractionNode = InteractionsList;

	while (tempInteractionNode)
	{
		
		out << "Link,\"MyLink";
		out << i++;

		if (!strcmp(tempInteractionNode->effect, "+"))
		{
			out << "\",\"Positive connector\",,\"";
		}
		else if (!strcmp(tempInteractionNode->effect, "_"))
		{
			out << "\",\"Negative connector\",,\"";
		}
		else if (!strcmp(tempInteractionNode->effect, "0"))
		{
			out << "\",\"No effect connector\",,\"";
		}
		
		out << tempInteractionNode->source;

		out << "\",\"";
		
		out << tempInteractionNode->target;
		
		out << "\"\n";

		i++;

		tempInteractionNode = tempInteractionNode->next;
	}
	
	out.close();
}

char* GetVisioShape(char* moleculeType)
{
	VISIO_SHAPE* tempNode;

	tempNode = VisioShapesList;

	while (tempNode)
	{
		if (!strcmp(tempNode->moleculeType, moleculeType))
		{
			return tempNode->shape;
		}
		tempNode = tempNode->next;
	}

	return DefaultVisioShape;
}

int GetLevelBaseOnLocation(char* location)
{

	if (!strcmp(location, "Extracellular"))
	{
		return 12;
	}
	if (!strcmp(location, "Membrane"))
	{
		return 10;
	}
	if (!strcmp(location, "CytosolM"))
	{
		return 3;
	}
	if (!strcmp(location, "Cytosol"))
	{
		return 2;
	}
	if (!strcmp(location, "Nucleus"))
	{
		return 1;
	}
	return 2;
}

void LoadVisioShapes(void)
{
	ifstream inputFile;
	VISIO_SHAPE* tempNode;
	int count = 0;
	inputFile.open("visio_shapes.txt");

	while (!inputFile.eof())
	{		
		if (!count)
		{
			VisioShapesList = (VISIO_SHAPE*) malloc(sizeof(VISIO_SHAPE));
			tempNode = VisioShapesList;
		}
		else
		{
			tempNode->next = (VISIO_SHAPE*) malloc(sizeof(VISIO_SHAPE));
			tempNode = tempNode->next;
		}
		tempNode->next = 0;

		inputFile >> tempNode->moleculeType >> tempNode->shape;
		count++;
	}

	inputFile.close();

	return;
}

void GetXLocation(char* location)
{
	int temp;
	double temp1;

	if (!strcmp(location, "Extracellular"))
	{
		temp = 15 + ExtracellularCount * 2;
		XLocationNumber = temp;
		itoa(temp, XLocation, 10);
	}
	else if (!strcmp(location, "Membrane"))
	{
		temp1 = MembraneCount * 1.05;
		XLocationNumber = temp1;
		sprintf(XLocation, "%.2f", temp1);
	}
	else if (!strcmp(location, "Cytosol"))
	{
		temp = 15 + (CytoCount % 10) * 3;
		XLocationNumber = temp;
		itoa(temp, XLocation, 10);
	}
	if (!strcmp(location, "Nucleus"))
	{
		temp = 2 + (NucleusCount % 5) * 2;
		XLocationNumber = temp;
		itoa(temp, XLocation, 10);
	}
	else if (!strcmp(location, "ER"))
	{
		temp = 2 + (ERCount % 5) * 2;
		XLocationNumber = temp;
		itoa(temp, XLocation, 10);
	}
	else if (!strcmp(location, "Ribosome"))
	{
		temp = 45 + (RiboCount % 5) * 2;
		XLocationNumber = temp;
		itoa(temp, XLocation, 10);
	}
	else if (!strcmp(location, "Mitochondria"))
	{
		temp = 45 + (MitoCount % 5) * 2;
		XLocationNumber = temp;
		itoa(temp, XLocation, 10);
	}
	else if (!strcmp(location, "Vesicles"))
	{
		temp = 45 + (VesicleCount % 5) * 2;
		XLocationNumber = temp;
		itoa(temp, XLocation, 10);
	}
	else if (!strcmp(location, "Cytoskeleton"))
	{
		temp = 45 + (SkeletonCount % 5) * 2;
		XLocationNumber = temp;
		itoa(temp, XLocation, 10);
	}

}
void GetYLocation(char* location)
{
	int temp;
	double temp1;

	if (!strcmp(location, "Extracellular"))
	{
		ExtracellularCount++;
		itoa(35, YLocation, 10);
		YLocationNumber = 35;
	}
	else if (!strcmp(location, "Membrane"))
	{
		MembraneCount++;
		itoa(32, YLocation, 10);
		YLocationNumber = 32;
	}
	else if (!strcmp(location, "Cytosol"))
	{
		temp1 = 7 + ((CytoCount / 10) * 1.1);
		sprintf(YLocation, "%.2f", temp1);
		YLocationNumber = temp1;
		CytoCount++;
	}
	if (!strcmp(location, "Nucleus"))
	{
		temp = 7 + ((NucleusCount / 5) * 1);
		itoa(temp, YLocation, 10);
		YLocationNumber = temp;
		NucleusCount++;
	}
	else if (!strcmp(location, "ER"))
	{
		temp = 20 + ((ERCount / 5) * 1);
		itoa(temp, YLocation, 10);
		YLocationNumber = temp;
		ERCount++;
	}
	else if (!strcmp(location, "Ribosome"))
	{
		temp = 14 + ((RiboCount / 5) * 1);
		itoa(temp, YLocation, 10);
		YLocationNumber = temp;
		RiboCount++;
	}
	else if (!strcmp(location, "Mitochondria"))
	{
		temp = 20 + ((MitoCount / 5) * 1);
		itoa(temp, YLocation, 10);
		YLocationNumber = temp;
		MitoCount++;
	}
	else if (!strcmp(location, "Vesicles"))
	{
		temp = 7 + ((VesicleCount / 5) * 1);
		itoa(temp, YLocation, 10);
		YLocationNumber = temp;
		VesicleCount++;
	}
	else if (!strcmp(location, "Cytoskeleton"))
	{
		temp = 7 + ((SkeletonCount / 5) * 1);
		itoa(temp, YLocation, 10);
		YLocationNumber = temp;
		SkeletonCount++;
	}
}

void CTestSVGDlg::OnButton3() 
{
	ifstream svgFile;
	ofstream out;
	CString temp1;
	CString temp2;
	CString temp3;
	MOLECULE* tempNode;

	tempNode = MoleculesList;

	out.open("list.txt");

	while (tempNode)
	{

		out << tempNode->name << endl;

		tempNode = tempNode->next;

	}

	out.close();

	AfxMessageBox("Done 1!");

	return;

}

void CTestSVGDlg::OnButton4() 
{
	MOLECULE* tempNode;
	INTERACTION* tempInt;
	ofstream out;

	out.open("without_conflicts.sig");

	tempInt = InteractionsList;

	while (tempInt)
	{
		tempNode = MoleculesList;

		while (tempNode)
		{
			if (!strcmp(tempNode->name, tempInt->source))
			{
				break;
			}
			tempNode = tempNode->next;
		}
		out << tempNode->name << " " << tempNode->accHuman << " " << tempNode->accMouse << " " << tempNode->moleculeType << " " << tempNode->location << " ";

		tempNode = MoleculesList;

		while (tempNode)
		{
			if (!strcmp(tempNode->name, tempInt->target))
			{
				break;
			}
			tempNode = tempNode->next;
		}
		out << tempNode->name << " " << tempNode->accHuman << " " << tempNode->accMouse << " " << tempNode->moleculeType << " " << tempNode->location << " ";
		out << tempInt->effect << " " << tempInt->typeOfInteraction << " " << tempInt->pmid << endl;
		tempInt = tempInt->next;
	}

	AfxMessageBox("3- Done!");
}

void CTestSVGDlg::OnButtonNet() 
{
	ifstream connections;
    ofstream graph;
	MOLECULE* tempNode;
	MOLECULE* tempNode1;
	INTERACTION* tempInteraction;    
	int ret;

	CFileDialog myDialog(FALSE, NULL, "*.net", OFN_OVERWRITEPROMPT, NULL, NULL );

	ret = myDialog.DoModal();

	if (ret == IDCANCEL)
	{
		return;
	}
	
	graph.open(myDialog.m_ofn.lpstrFile);

	char colorAndShape[100];
	char moleculeTypeIndex;
    
	//TakeOutTheHubs();
	
	graph << "*Vertices    " << NumberOfMolecules << endl;

	tempNode = MoleculesList;

	while (tempNode)
	{
		moleculeTypeIndex = GetMoleculeTypeIndex(tempNode->moleculeType);

		GetColorAndShape(moleculeTypeIndex, colorAndShape);

		if (!strcmp(tempNode->moleculeType, "Ligand"))
		{
			graph << tempNode->number << "  " << "\"" << tempNode->name << "\"" << "ic Orange ellipse" << endl;
		}
		else if (!strcmp(tempNode->moleculeType, "Cytoskeleton"))
		{
			graph << tempNode->number << "  " << "\"" << tempNode->name << "\"" << " ic Goldenrod ellipse" << endl;
		}
		else if (!strcmp(tempNode->moleculeType, "TF"))
		{
			graph << tempNode->number << "  " << "\"" << tempNode->name << "\"" << " ic SkyBlue ellipse" << endl;
		}
		else if (!strcmp(tempNode->location, "ER"))
		{
			graph << tempNode->number << "  " << "\"" << tempNode->name << "\"" << " ic Priwinkle ellipse" << endl;
		}
		else if (!strcmp(tempNode->location, "Membrane"))
		{
			graph << tempNode->number << "  " << "\"" << tempNode->name << "\"" << " ic Orchid ellipse" << endl;
		}
		else if (!strcmp(tempNode->location, "Vesicles"))
		{
			graph << tempNode->number << "  " << "\"" << tempNode->name << "\"" << " ic Periwinkle ellipse" << endl;
		}
		else if (!strcmp(tempNode->location, "Cytosol"))
		{
			graph << tempNode->number << "  " << "\"" << tempNode->name << "\"" << " ic Blue ellipse" << endl;
		}
		else
		{
			graph << tempNode->number << "  " << "\"" << tempNode->name << "\"" << " ic Gray20 ellipse" << endl;
		}
		tempNode = tempNode->next;
	}


	graph << "*Arcs" << endl;

	tempInteraction = InteractionsList;

	while (tempInteraction)
    { 
	    tempNode = GetNodeBasedOnName(tempInteraction->source);
		tempNode1 = GetNodeBasedOnName(tempInteraction->target);

		if (!strcmp(tempInteraction->effect, "+"))
		{
			graph << "   " << GetNumberBasedOnString(tempInteraction->source) << "    ";
			graph << GetNumberBasedOnString(tempInteraction->target) << "    " <<  "1 c PineGreen" << endl;
		}
		else if (!strcmp(tempInteraction->effect, "_"))
		{
			graph << "   " << GetNumberBasedOnString(tempInteraction->source) << "    ";
			graph << GetNumberBasedOnString(tempInteraction->target) << "    " <<  "1 c Red" << endl;
		} 
		

		tempInteraction = tempInteraction->next;
    }
	
	graph << "*Edges" << endl;

	tempInteraction = InteractionsList;

	while (tempInteraction)
    { 
	    tempNode = GetNodeBasedOnName(tempInteraction->source);
		tempNode1 = GetNodeBasedOnName(tempInteraction->target);

		if (!strcmp(tempInteraction->effect, "0"))
		{
			graph << "   " << GetNumberBasedOnString(tempInteraction->source) << "    ";
			graph << GetNumberBasedOnString(tempInteraction->target) << "    " <<  "1 c Blue" << endl;
		}

		tempInteraction = tempInteraction->next;
    }

	graph.close();

	MessageBox("Done!", "Finished creating file for Pajek", MB_OK | MB_ICONINFORMATION);
    return;	
	
}

void GetColorAndShape(int moleculeTypeIndex, char* colorAndShape)
{
	switch (moleculeTypeIndex)
	{
	case 1:
		strcpy(colorAndShape, " ic Blue ellipse"); 
		break;
	case 2:
		strcpy(colorAndShape, " ic Blue box"); 
		break;
	case 3:
		strcpy(colorAndShape, " ic Blue diamond"); 
		break;
	case 4:
		strcpy(colorAndShape, " ic Red ellipse"); 
		break;
	case 5:
		strcpy(colorAndShape, " ic Red box"); 
		break;
	case 6:
		strcpy(colorAndShape, " ic Red diamond"); 
		break;
	case 7:
		strcpy(colorAndShape, " ic Green ellipse"); 
		break;
	case 8:
		strcpy(colorAndShape, " ic Green box"); 
		break;
	case 9:
		strcpy(colorAndShape, " ic Green diamond"); 
		break;
	case 10:
		strcpy(colorAndShape, " ic Yellow ellipse"); 
		break;
	case 11:
		strcpy(colorAndShape, " ic Yellow box"); 
		break;
	case 12:
		strcpy(colorAndShape, " ic Yellow diamond"); 
		break;
	case 13:
		strcpy(colorAndShape, " ic CornflowerBlue ellipse"); 
		break;
	case 14:
		strcpy(colorAndShape, " ic CornflowerBlue box"); 
		break;
	case 15:
		strcpy(colorAndShape, " ic CornflowerBlue diamond"); 
		break;
	case 16:
		strcpy(colorAndShape, " ic RubineRed ellipse"); 
		break;
	case 17:
		strcpy(colorAndShape, " ic RubineRed box"); 
		break;
	case 18:
		strcpy(colorAndShape, " ic RubineRed diamond"); 
		break;
	case 19:
		strcpy(colorAndShape, " ic SpringGreen ellipse"); 
		break;
	case 20:
		strcpy(colorAndShape, " ic SpringGreen box"); 
		break;
	case 21:
		strcpy(colorAndShape, " ic Lavender ellipse"); 
		break;
	case 22:
		strcpy(colorAndShape, " ic Lavender box"); 
		break;
	case 23:
		strcpy(colorAndShape, " ic Lavender diamond"); 
		break;
	case 24:
		strcpy(colorAndShape, " ic Tan ellipse"); 
		break;
	case 25:
		strcpy(colorAndShape, " ic Tan box"); 
		break;
	case 26:
		strcpy(colorAndShape, " ic Tan diamond"); 
		break;
	case 27:
		strcpy(colorAndShape, " ic YellowOrange ellipse"); 
		break;
	case 28:
		strcpy(colorAndShape, " ic YellowOrange box"); 
		break;
	case 29:
		strcpy(colorAndShape, " ic YellowOrange diamond"); 
		break;
	default:
		strcpy(colorAndShape, " ic YellowOrange diamond"); 
		break;
	}
}

int GetMoleculeTypeIndex(char* moleculeType)
{
	int i; 

	for (i = 0; i < CountOfMoleculeTypes; i++)
	{
		if (!strcmp(moleculeType, MoleculeTypesNames[i]))
		{
			return i;
		}
	}

	return 0;
}

void CTestSVGDlg::OnButtonRandom() 
{
	int i, j;
	int done, done1;
	ofstream outputFile;
    int randomComponent;
	int numberOfLinks;
	int randomTarget;
	int randomConnectorIndex;
	int randomConnector;
	int numberOfConnections = 0;
	CFileDialog myDialog(TRUE, NULL, "*.sig", OFN_OVERWRITEPROMPT, NULL, NULL );

	myDialog.DoModal();

	outputFile.open(myDialog.m_ofn.lpstrFile);

	InitArrayOfConnectivity();

	InitArrayOfConnectors();

	CountOfRandomConnections = 0;

	for (i = 1; i <= NumberOfMolecules; i++)
	{
		done = 0;
		while (!done)
		{
			randomComponent = GetRandomNumber(NumberOfMolecules);
			
			if (CheckIfArrayOfConnectivityIsEmpty())
			{
				outputFile.close();
				return;
			}

			if (ArrayOfConnectivity[randomComponent])
			{
				numberOfLinks = ArrayOfConnectivity[randomComponent];
				ArrayOfConnectivity[randomComponent] = 0;
				done = 1;
			}
		}

		for (j = 0; j < numberOfLinks; j++)
		{
			done = 0;
			while (!done)
			{
				randomTarget = GetRandomNumber(NumberOfMolecules);
				
				//outputFile.close();

				if ((ArrayOfConnectivity[randomTarget]) && (randomTarget != randomComponent) && (NotAlreadyDumpedRandomConnection(randomTarget, randomComponent)))
				{
					ArrayOfConnectivity[randomTarget]--;
					done1 = 0;
					while(!done1)
					{
						randomConnectorIndex = GetRandomNumber(NumberOfInteractions);

						if (ArrayOfConnectors[randomConnectorIndex])
						{
							randomConnector = ArrayOfConnectors[randomConnectorIndex];
							ArrayOfConnectors[randomConnectorIndex] = 0;
							done1 = 1;
						}
					}
					outputFile << "node" <<  randomComponent << " NoType NoLocation node" <<  randomTarget << " NoType NoLocation ";
					RandomSources[CountOfRandomConnections] = randomComponent;
					RandomTargets[CountOfRandomConnections] = randomTarget;
					CountOfRandomConnections++;
					if (randomConnector == 1)
					{
						outputFile << "+ NoType" << endl;
					}
					else if (randomConnector == 2)
					{
						outputFile << "_ NoType" << endl;
					}
					else if (randomConnector == 3)
					{
						outputFile << "0 NoType" << endl;
					}
					
					done = 1;
					numberOfConnections++;
				}
			}
		}
	}						
	outputFile.close();
	
	AfxMessageBox("Done2!");

}

int NotAlreadyDumpedRandomConnection(int randomTarget, int randomComponent)
{
	int i;
	for (i = 0; i < CountOfRandomConnections; i++)
	{
		if (((randomComponent == RandomSources[i]) && (randomTarget == RandomTargets[i])) ||  
			((randomTarget == RandomSources[i]) && (randomComponent == RandomTargets[i])))
		{
			return 0;
		}
	}

	return 1;
}

void InitArrayOfConnectivity(void)
{
	int i;

	MOLECULE* tempNode;

	tempNode = MoleculesList;

	i = 0;

	while (tempNode)
	{
		ArrayOfConnectivity[i] = tempNode->linksCount;
		i++;

		tempNode = tempNode->next;	
	}
}


int CheckIfArrayOfConnectivityIsEmpty(void)
{
	int i;
	for (i = 0; i < NumberOfMolecules; i++)
	{
		if (ArrayOfConnectivity[i])
		{
			return 0;
		}
	}
	return 1;
}

void InitArrayOfConnectors(void)
{
	INTERACTION* tempNode;
	int i;

	tempNode = InteractionsList;

	i = 0;

	while (tempNode)
	{
		if (!strcmp(tempNode->effect, "+"))
		{
			ArrayOfConnectors[i] = 1;
		}
		else if (!strcmp(tempNode->effect, "_"))
		{
			ArrayOfConnectors[i] = 2;
		}
		else if (!strcmp(tempNode->effect, "0"))
		{
			ArrayOfConnectors[i] = 3;
		}

		tempNode = tempNode->next;		
		
		i++;
	}
}

int GetRandomNumber(int range)
{
	return rand() % range;
}

void CTestSVGDlg::OnButtonRandomSign() 
{
	INTERACTION* tempNode;
	int numberOfPlus = 0;
	int numberOfMinus = 0;
	int numberOfZero = 0;
	int i;
	ofstream out;
	int randomNumber;

	out.open("random_direction.sig");

	tempNode = InteractionsList;

	i = 0;

	while (tempNode)
	{
		if (!strcmp(tempNode->effect, "+"))
		{
			numberOfPlus++;
		}
		else if (!strcmp(tempNode->effect, "_"))
		{
			numberOfMinus++;
		}
		else if (!strcmp(tempNode->effect, "0"))
		{
			numberOfZero++;
		}

		tempNode = tempNode->next;		
		
		i++;
	}

	InitArrayOfConnectors();

	out << "NA" << endl;
	out << "NA" << endl;
	out << "NA" << endl;
	out << "NA" << endl;
	out << i << endl;

	tempNode = InteractionsList;

	while (tempNode)
	{
		//either put the source or the target first or second
		randomNumber = GetRandomNumber(i);

		out << tempNode->source << " " << tempNode->sourceType << " " << tempNode->sourceLocation << " " << tempNode->target << " ";
		out << tempNode->targetType << " " << tempNode->targetLocation;

		if (ArrayOfConnectors[i] == 3)
		{
			out << " 0 ";
		}
		else if (ArrayOfConnectors[i] == 2)
		{
			out << " - ";
		}
		else if (ArrayOfConnectors[i] == 1)
		{
			out << " + ";
		}
		else
		{
			out << " ? ";
		}

		out << tempNode->typeOfInteraction << endl;

		tempNode = tempNode->next;
	}

	AfxMessageBox("Done3!");
}

void TakeOutTheHubs(void)
{
	MOLECULE* tempNode;
	MOLECULE* tempNode1;
	int number, i;
	
	tempNode = MoleculesList;

	while (tempNode)
	{
		if (tempNode->linksCount > 10)
		{
			for (i = 0; i < tempNode->linksCount; i++)
			{
				number = tempNode->linksTo[i];
				tempNode1 = GetNodeBasedOnNumber(number);
				tempNode1->linksCount--;
			}
			tempNode->linksCount = 0;
		}
		tempNode = tempNode->next;
	}
	
	return;	
}


void CTestSVGDlg::OnButtonInteractionsMatrix() 
{
	CDialogInteractionsMatrix myDialog;

	myDialog.DoModal();
}

void CTestSVGDlg::OnButtonAddPhosphatases() 
{
	
}

void CTestSVGDlg::OnButtonMotifsInput() 
{
	ifstream connections;
    ofstream graph;
	MOLECULE* tempNode;
	MOLECULE* tempNode1;
	INTERACTION* tempInteraction;
	ofstream names;
	int ret;

	CFileDialog myDialog(FALSE, NULL, "input_for_mfinder.txt", OFN_OVERWRITEPROMPT, NULL, NULL );

	ret = myDialog.DoModal();

	if (ret == IDCANCEL)
	{
		return;
	}

	graph.open(myDialog.m_ofn.lpstrFile);
    names.open("names.txt");

	tempInteraction = InteractionsList;

	while (tempInteraction)
    { 
	    tempNode = GetNodeBasedOnName(tempInteraction->source);
		tempNode1 = GetNodeBasedOnName(tempInteraction->target);

		if (GetNumberBasedOnString(tempInteraction->target) != GetNumberBasedOnString(tempInteraction->source))
		{
			
		    if (!strcmp(tempInteraction->effect, "0"))
		    {
			    graph << "   " << GetNumberBasedOnString(tempInteraction->target) << "    ";
			    graph << GetNumberBasedOnString(tempInteraction->source)  << "    " <<  "1" << endl;
		    }
		    graph << "   " << GetNumberBasedOnString(tempInteraction->source) << "    ";
		    graph << GetNumberBasedOnString(tempInteraction->target) << "    " <<  "1" << endl;
		}
		
		tempInteraction = tempInteraction->next;
    }
	
	graph.close();

	tempNode = MoleculesList;

	while (tempNode)
	{
		names << tempNode->number << " " << tempNode->name << endl;
		tempNode =  tempNode->next;
	}

	names.close();

	MessageBox("Done!", "Creating file for MFinder", MB_OK | MB_ICONINFORMATION);
    return;	
	
}

void CTestSVGDlg::OnButtonRandom100() 
{
	INTERACTION* tempNode;
	INTERACTION* tempNode1;
	INTERACTION* tempNode2;
	ofstream out;
	int randomNumber;
	char fileName[100];
	char tempStr[100];
	int i, j;

	for (i = 1; i < 100; i++)
	{
		sprintf(fileName, "random_net%d.sig", i);

		out.open(fileName);

		tempNode = InteractionsList;

		out << "NA" << endl;
		out << "NA" << endl;
		out << "NA" << endl;
		out << "NA" << endl;
		out << NumberOfInteractions << endl;

		tempNode1 = InteractionsList;

		while (tempNode1)
		{
			randomNumber = GetRandomNumber(NumberOfInteractions);

			tempNode2 = InteractionsList;
	
			for (j = 0; j < randomNumber; j++)
			{
				tempNode2 = tempNode2->next;
			}

			if ((tempNode1 != tempNode2) && (ThereIsNoLinkAlready(tempNode1, tempNode2)))
			{
				
				strcpy(tempStr, tempNode1->target);
				strcpy(tempNode1->target, tempNode2->target);
				strcpy(tempNode2->target, tempStr);
			}
			tempNode1 = tempNode1->next;
		}


		tempNode = InteractionsList;


		while (tempNode)
		{
			
			out << tempNode->source << " " << tempNode->sourceType << " " << tempNode->sourceLocation << " " << tempNode->target << " ";
			out << tempNode->targetType << " " << tempNode->targetLocation << " " << tempNode->effect << " " << tempNode->typeOfInteraction << endl;
			
			tempNode = tempNode->next;
		}

		out.close();
	}

	AfxMessageBox("Done5!");
	
}

// if there is already a link between the source and the target we are about to swap don't do it
int ThereIsNoLinkAlready(INTERACTION* interaction1, INTERACTION* interaction2)
{
	INTERACTION* tempNode;
	
	tempNode = InteractionsList;
	
	while (tempNode)
	{

		if	(
			((!strcmp(interaction2->source, tempNode->source)) &&
			(!strcmp(interaction1->target, tempNode->target)))
			||
			((!strcmp(interaction1->source, tempNode->source)) &&
			(!strcmp(interaction2->target, tempNode->target)))
			||
			((!strcmp(interaction1->target, tempNode->source)) &&
			(!strcmp(interaction2->source, tempNode->target)))
			||
			((!strcmp(interaction2->target, tempNode->source)) &&
			(!strcmp(interaction1->source, tempNode->target)))
			)
		{	
			return 0;
		}

		tempNode = tempNode->next;
	}

	return 1;
}


void CTestSVGDlg::OnButton10() 
{
	int i;
	ofstream out;
	ifstream inputFile;
    char fileName[100];

	out.open("c://cc_and_cpl.htm");

	out << "<html><body><table><tr><td>Network</td><td>CC</td><td>CPL</td></tr>" << endl;

	CFileDialog myDialog(TRUE, NULL, "*.sig", OFN_OVERWRITEPROMPT, NULL, NULL );

	myDialog.DoModal();

	LoadNetwork(myDialog.m_ofn.lpstrFile);

	out << "<tr><td>Real Network</td><td>" << ComputeCC() << "</td><td>" << ComputeAvgPathLength() << "</td></tr>" << endl;

	FreeNetwork();

	for (i = 1; i <= 100; i++)
	{
		sprintf(fileName, "random_net%d.sig", i);

		LoadNetwork(fileName);

		out << "<tr><td>Random Network #" << i << "</td><td>" << ComputeCC() << "</td><td>" << ComputeAvgPathLength() << "</td></tr>" << endl;

		FreeNetwork();
	}

	out << "</table></body></html>";

	out.close();

	AfxMessageBox("Done6!");
	
}


void FreeMoleculesList(void)
{
	MOLECULE* tempNode;

	tempNode = MoleculesList;

	while (MoleculesList)
	{
		MoleculesList = tempNode->next;
		free(tempNode);
		tempNode = MoleculesList;
	}

	NumberOfMolecules = 0;
	return;
}


void FreeInteractionsList(void)
{
	INTERACTION* tempNode;

	tempNode = InteractionsList;

	while (InteractionsList)
	{
		InteractionsList = tempNode->next;
		free(tempNode);
		tempNode = InteractionsList;
	}

	NumberOfInteractions = 0;
	return;
}


void CTestSVGDlg::OnButtonFigure3() 
{
	ifstream connections;
    ofstream graph;
	MOLECULE* tempNode;
	MOLECULE* tempNode1;
	INTERACTION* tempInteraction;    
	graph.open("figure3.net");
	char colorAndShape[100];
	char moleculeTypeIndex;
    
	//TakeOutTheHubs();
	
	graph << "*Vertices    " << NumberOfMolecules << endl;


	tempNode = MoleculesList;


	while (tempNode)
	{
		moleculeTypeIndex = GetMoleculeTypeIndex(tempNode->moleculeType);

		GetColorAndShape(moleculeTypeIndex, colorAndShape);

		if (tempNode->linksCount > 15)
		{
			graph << tempNode->number << "  " << "\"" << tempNode->name << "\"" << " ic Yellow ellipse" << endl;
		}
		else 
		{
			graph << tempNode->number << "  " << "\"" << tempNode->name << "\"" << " ic Cerulean ellipse" << endl;
		}
		
		tempNode = tempNode->next;
	}


	graph << "*Arcs" << endl;


	tempInteraction = InteractionsList;

	while (tempInteraction)
    { 
	    tempNode = GetNodeBasedOnName(tempInteraction->source);
		tempNode1 = GetNodeBasedOnName(tempInteraction->target);

		//if ((tempNode->linksCount <= 15) && (tempNode1->linksCount <= 15))
		//{
		
		graph << "   " << GetNumberBasedOnString(tempInteraction->source) << "    ";
		graph << GetNumberBasedOnString(tempInteraction->target) << "    " <<  "1" << endl;
		
		
		//}

		tempInteraction = tempInteraction->next;
    }
	
	graph.close();

	AfxMessageBox("Done7!");
    return;	
	
}

int IsItNegativeLoop(int* listSoFar, int size)
{
	INTERACTION* node;
	MOLECULE* source;
	MOLECULE* target;
	int i;

	int negatives = 0;

	for (i = 0; i < size - 1; i++)
	{
		source = GetNodeBasedOnNumber(listSoFar[i]);
		target = GetNodeBasedOnNumber(listSoFar[i + 1]);
	
		node = InteractionsList;

		while (node)
		{
			if (((!strcmp(node->source, source->name)) && (!strcmp(node->target, target->name))) || 
				((!strcmp(node->target, source->name)) && (!strcmp(node->source, target->name))))
			{
				if (!strcmp(node->effect, "_"))
				{
					negatives++;
				}

				break;
			}
			node = node->next;
		}		
	}

	source = GetNodeBasedOnNumber(listSoFar[i]);
	target = GetNodeBasedOnNumber(listSoFar[0]);
	
	node = InteractionsList;

	while (node)
	{
		if (((!strcmp(node->source, source->name)) && (!strcmp(node->target, target->name))) || 
			((!strcmp(node->target, source->name)) && (!strcmp(node->source, target->name))))
		{
			if (!strcmp(node->effect, "_"))
			{
				negatives++;
			}

			break;
		}
		node = node->next;
	}	

	if (negatives % 2)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}


int IsItNegativePathway(int* listSoFar, int size)
{
	INTERACTION* node;
	MOLECULE* source;
	MOLECULE* target;
	int i;
	int negatives = 0;

	for (i = 0; i < size - 2; i++)
	{
		source = GetNodeBasedOnNumber(listSoFar[i]);
		target = GetNodeBasedOnNumber(listSoFar[i + 1]);
	
		node = InteractionsList;

		while (node)
		{
			if (((!strcmp(node->source, source->name)) && (!strcmp(node->target, target->name))) || 
				((!strcmp(node->target, source->name)) && (!strcmp(node->source, target->name))))
			{
				if (!strcmp(node->effect, "_"))
				{
					negatives++;
				}

				break;
			}
			node = node->next;
		}		
	}

	if (negatives % 2)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

void CTestSVGDlg::OnButtonPubmed() 
{
	INTERACTION* tempNode;
	COleDateTime today = COleDateTime::GetCurrentTime();
	ifstream inlist;
	CString theString;
	LPTSTR strObject = new TCHAR[200];
	char tempStr[100];
	char dummy[100];
	ofstream temp;
	int dwRet;
    int count = 0;
	ofstream debug;
	int length;
	int i;

	CInternetSession session("My Session");
	CHttpConnection* pServer = NULL;
	CHttpFile* pFile = NULL;
	CString strServerName = "www.ncbi.nlm.nih.gov";
	CString tempUrl;
	INTERNET_PORT nPort = 80;
	tempNode = InteractionsList;
	
	pServer = session.GetHttpConnection(strServerName, nPort);

	try
	{
		while (tempNode)
		{
			count++;
			
			for (i = 0; i < tempNode->referenceCount; i++)
			{

			//http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=1521331&retmode=mode
			tempUrl.Format("http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?cmd=Retrieve&db=pubmed&dopt=Abstract&list_uids=%d", tempNode->references[i]);

			tempUrl.Replace("http://www.ncbi.nlm.nih.gov", "");

			_tcscpy(strObject, tempUrl);
			
			pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject);
			
			pFile->AddRequestHeaders("test");
		
			pFile->SendRequest();
			
			dwRet = HTTP_STATUS_OK;
		 

			strcpy(tempStr, itoa(tempNode->references[i], dummy, 10));

			strcat(tempStr, ".htm");

			if (dwRet == HTTP_STATUS_OK)
			{
				temp.open(tempStr);
				
				try 
				{
					int count = 0;
					while (pFile->ReadString(szBuff, 4096))
					{
							length = strlen(szBuff);
							szBuff[length] = 0;
							temp << szBuff << endl;
					}
				}
				catch (CInternetException* pEx)
				{
					AfxMessageBox("You must be connected to the internet in order to download an update!");
				}
				temp.close();
			}

			delete pFile;
			
			} // end for loop
			tempNode = tempNode->next;
		}
	}
	catch (CInternetException* pEx)
	{
		AfxMessageBox("You must be connected to the internet in order to download an update!");
	}

	AfxMessageBox("Done8!");

	return;
}

void CTestSVGDlg::OnButtonIslands() 
{
	CDialogViewer viewerDialog;
		
	strcpy(viewerDialog.fileName, "http://amp.pharm.mssm.edu/SNAVI/help/getting_started.htm");
	viewerDialog.DoModal();
	
}

int CountIslands(void)
{
	MOLECULE* tempNode;
	int numberOfIslands = 0;
	int listSoFar[8000];
	int listSoFarIndex = 0;
	int previousListSoFarIndex;

	tempNode = MoleculesList;

	while (tempNode)
	{		
		previousListSoFarIndex = listSoFarIndex;
		listSoFarIndex = ExpandIsland(tempNode, listSoFar, listSoFarIndex);
		
		if (listSoFarIndex != previousListSoFarIndex)
		{
			numberOfIslands++;
		}
		tempNode = tempNode->next;
	}	

	return numberOfIslands; 
}

int ExpandIsland(MOLECULE* tempNode, int* listSoFar, int listSoFarIndex)
{
	int i;
	int alreadyExpanded = 0;
	MOLECULE* newTempNode;

	if (!tempNode)
	{
		alreadyExpanded = 1;
	}
	else
	{
		for (i = 0; i < listSoFarIndex; i++)
	    {
		    if (listSoFar[i] == tempNode->number)
		    {
			    alreadyExpanded = 1;
		    }
		}
	}

	if (!alreadyExpanded)
	{
		listSoFar[listSoFarIndex] = tempNode->number;
		listSoFarIndex++;

		for (i = 0; i < tempNode->linksCount; i++)
		{
			newTempNode = GetNodeBasedOnNumber(tempNode->linksTo[i]);
			listSoFarIndex = ExpandIsland(newTempNode, listSoFar, listSoFarIndex);
		}
	}

	return listSoFarIndex;
}

void CTestSVGDlg::OnButtonRemoveSelective() 
{
	INTERACTION* tempNode;
	MOLECULE* tempNode1;
	MOLECULE* tempNode2;
	ofstream out;
	int numberOfInteractions = 0;
	int j;
	char fileName[100];
	char pajekFileName[100];

	OnBnClickedButtonMachineCount();

	for (j = 1; j < 60; j++)
	{
		numberOfInteractions = 0;

		sprintf(fileName, "reduced_net%d.sig", j);
		sprintf(pajekFileName, "reduced_net%d.net", j);
		
		out.open(fileName);

		tempNode = InteractionsList;
		while (tempNode)
		{
			tempNode1 = GetNodeBasedOnName(tempNode->source);
			tempNode2 = GetNodeBasedOnName(tempNode->target);

			if ((tempNode1->linksCount <= j) && (tempNode2->linksCount <= j))
			{
				numberOfInteractions++;
			}
			
			tempNode = tempNode->next;
		}

		ClearInteractionsFlag();

		tempNode = InteractionsList;

		while (tempNode)
		{
			tempNode1 = GetNodeBasedOnName(tempNode->source);
			tempNode2 = GetNodeBasedOnName(tempNode->target);

			if ((tempNode1->linksCount <= j) && (tempNode2->linksCount <= j))
			{
				out << tempNode->source << " " << tempNode->sourceAccHuman << " " << tempNode->sourceAccMouse << " " << tempNode->sourceType << " " << tempNode->sourceLocation << " " << tempNode->target << " " << tempNode->targetAccHuman << " " << tempNode->targetAccMouse << " ";
				out << tempNode->targetType << " " << tempNode->targetLocation << " " << tempNode->effect << " " << tempNode->typeOfInteraction << " " << tempNode->pmid << endl;
				tempNode->flag = 1;
			}

			tempNode = tempNode->next;
		}
		
		DumpFlaggedInteractionsToPajek(pajekFileName);

		out.close();
	}

	AfxMessageBox("13- Done!");
	
}

void CTestSVGDlg::OnButtonRandomIslands() 
{
	
	AfxMessageBox("Done9!");
	
}

void CTestSVGDlg::OnButtonRandomIslandsNets() 
{
	
}

void CTestSVGDlg::OnButtonSubVisioMaps() 
{
	ifstream shortList;
	ofstream out;
	INTERACTION* tempInteractionNode;
	MOLECULE* tempNode;
	MOLECULE* tempNode2;
	char component[100];
	int level;
	int xLocations[10];
	int i, m;
	int alreadyList[1000];
	int alreadyCount = 0;
	int alreadyFlag;

	for (i = 0; i < 10; i++)
	{
		xLocations[i] = 1;
	}

	out.open("visio_input_short_list.txt");

	out << "Template, Basic Flowchart.vst\n";
	out << "Master,,\"Receptor\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Channel\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Cytoskeleton\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Protease\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Adhesion\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Activator\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"GEF\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Kinase\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Adapter\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Lipid\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"TF\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Ribosome\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"G_protein\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Phosphatase\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Messenger\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Cyclase\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Phospholipase\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"RNA\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Bcl2Family\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"PDE\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Adapter\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Synthase\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Ubiquitinase\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"GAP\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Ion\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Positive connector\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"Negative connector\",\"Cell Signaling.vss\"\n";
	out << "Master,,\"No effect connector\",\"Cell Signaling.vss\"\n";

	shortList.open("short_list.txt");

	while (!shortList.eof())
	{
		shortList >> component;

		tempNode = GetNodeBasedOnName(component);
		
		alreadyFlag = 0;

		for (m = 0; m < alreadyCount; m++)
		{
			if (alreadyList[i] == tempNode->number)
			{
				alreadyFlag = 1;
				break;
			}
		}
		
		if (!alreadyFlag)
		{
			alreadyList[alreadyCount] = tempNode->number;
			alreadyCount++;
		
		
			level = GetLevelBaseOnLocation(tempNode->location);
			out << "Shape,\"";
			out << tempNode->name;
			out << "\",\"";
			out << GetVisioShape(tempNode->moleculeType);
			out << "\",\"";
			out << tempNode->name;
			out << "\",";
			//GetXLocation(tempNode->location);
			//out << XLocation;
			out << xLocations[level - 1] % 14;
			xLocations[level - 1]++;
			out << ",";
			//GetYLocation(tempNode->location);
			//out << YLocation;
			out << level + (xLocations[level - 1] / 10);
			out << ",,,,,,\n";
		}
#ifdef AVI	
		for (i = 0; i < tempNode->linksCount; i++)
		{

			tempNode2 = GetNodeBasedOnNumber(tempNode->linksTo[i]);

			alreadyFlag = 0;

			for (m = 0; m < alreadyCount; m++)
			{
				if (alreadyList[i] == tempNode->number)
				{
					alreadyFlag = 1;
					break;
				}
			}
		
			if (!alreadyFlag)
			{
				level = GetLevelBaseOnLocation(tempNode2->location);
				out << "Shape,\"";
				out << tempNode2->name;
				out << "\",\"";
				out << GetVisioShape(tempNode2->moleculeType);
				out << "\",\"";
				out << tempNode2->name;
				out << "\",";
			//GetXLocation(tempNode->location);
			//out << XLocation;
				out << xLocations[level - 1] % 14;
				xLocations[level - 1]++;
				out << ",";
			//GetYLocation(tempNode->location);
			//out << YLocation;
				out << level;
				out << ",,,,,,\n";
			}
		}
#endif
	}

	shortList.close();
	
	i = 1;
	shortList.open("short_list.txt");

	while (!shortList.eof())
	{
		shortList >> component;

		tempNode = GetNodeBasedOnName(component);

		for (int j = 0; j < tempNode->linksCount; j++)
		{

			tempNode2 = GetNodeBasedOnNumber(tempNode->linksTo[j]);

			alreadyFlag = 0;

			for (m = 0; m < alreadyCount; m++)
			{
				if (alreadyList[i] == tempNode2->number)
				{
					alreadyFlag = 1;
					break;
				}
			}
		
			if (alreadyFlag)
			{
			

			tempInteractionNode = GetInteraction(tempNode->name, tempNode2->name);

			if (!tempInteractionNode)
			{
				tempInteractionNode = GetInteraction(tempNode2->name, tempNode->name);

				out << "Link,\"MyLink";
				out << i++;

				if (!strcmp(tempInteractionNode->effect, "+"))
				{
					out << "\",\"Positive connector\",,\"";
				}
				else if (!strcmp(tempInteractionNode->effect, "_"))
				{
					out << "\",\"Negative connector\",,\"";
				}
				else if (!strcmp(tempInteractionNode->effect, "0"))
				{
					out << "\",\"No effect connector\",,\"";
				}
		
				out << tempInteractionNode->target;

				out << "\",\"";
		
				out << tempInteractionNode->source;
		
				out << "\"\n";

				i++;
			}
			else
			{
				out << "Link,\"MyLink";
				out << i++;

				if (!strcmp(tempInteractionNode->effect, "+"))
				{
					out << "\",\"Positive connector\",,\"";
				}
				else if (!strcmp(tempInteractionNode->effect, "_"))
				{
					out << "\",\"Negative connector\",,\"";
				}
				else if (!strcmp(tempInteractionNode->effect, "0"))
				{
					out << "\",\"No effect connector\",,\"";
				}
		
				out << tempInteractionNode->source;

				out << "\",\"";
		
				out << tempInteractionNode->target;
		
				out << "\"\n";

				i++;
			}

			}

		}
	}
	AfxMessageBox("Done10!");
	out.close();
}

INTERACTION* GetInteraction(char* source, char* target)
{
	INTERACTION* tempNode;


	tempNode = InteractionsList;

	while (tempNode)
	{
		if ((!strcmp(source, tempNode->source)) && (!strcmp(target, tempNode->target)))
		{
			return tempNode;
		}
		tempNode = tempNode->next;
	}

	return 0;

}

void CTestSVGDlg::OnButtonSimGluAndNe() 
{
	//LoadMachines();
	//SimulateAllLigands();
	//SimulateLigandPairs("GLUTAMATE", "NE");
	//SimulateLigandPairs("GLUTAMATE", "BDNF");
	//SimulateLigandPairs("NE", "BDNF");
	SimulateArp23AndAMPAR();
	//SimulateAllTFs();
	//SimulateAllAtOnce();
	//SimulateCREB();
	//SimulatePQ_Type_Ca();
	//SimulateGlutamate();
	//SimulateNE();
	//SimulateBothGlutamateAndNE();
	//SimulateGABA();
	//SimulateAch();
	//SimulateFasL();
	AfxMessageBox("Done11!");
}



void SimulateGABA(void)
{
	MOLECULE* startNode;
	int i;
	ofstream out;
	int count = 0;
	out.open("just_gaba_sim.htm");

	out << "<HTML><BODY><TABLE>";

	for (i = 1; i <= 15; i++)
	{
		ClearVisitedFlagForAllMolecules();
		
		count = 0;
		
		//Search for glutame molecule
		startNode = GetNodeBasedOnName("GABA");

		count = ExpandSim(startNode, i, count);

		out << "<TR><TD>" << count << "</TD></TR>";
		
	}

	out << "</TABLE></BODY></HTML>";

	out.close();
}

void SimulateCREB(void)
{
	MOLECULE* startNode;
	int i;
	ofstream out;
	int count = 0;
	char fileName[100];

	out.open("creb_sim.htm");
	
	out << "<HTML><BODY><TABLE>";

	for (i = 1; i <= 15; i++)
	{
		ClearVisitedFlagForAllMolecules();
		
		count = 0;
		
		//Search for glutame molecule
		startNode = GetNodeBasedOnName("CREB");

		count = ExpandReverseSim(startNode, i, count);

		count = CountAllVisited();
				
		sprintf(fileName, "%s_sub_net_depth%d.sig", startNode->name, i);

		startNode->visited = 1;
				
		DumpAllVisited(fileName);

		out << "<TR><TD>" << count << "</TD></TR>";
		
	}

	out << "</TABLE></BODY></HTML>";

	out.close();
}
void SimulateFasL(void)
{
	MOLECULE* startNode;
	int i;
	ofstream out;
	int count = 0;
	out.open("just_fasl_sim.htm");

	out << "<HTML><BODY><TABLE>";

	for (i = 1; i <= 15; i++)
	{
		ClearVisitedFlagForAllMolecules();
		
		count = 0;
		
		//Search for glutame molecule
		startNode = GetNodeBasedOnName("FasL");

		count = ExpandSim(startNode, i, count);

		out << "<TR><TD>" << count << "</TD></TR>";
		
	}

	out << "</TABLE></BODY></HTML>";

	out.close();
}

void SimulatePQ_Type_Ca(void)
{
	MOLECULE* startNode;
	int i;
	ofstream out;
	int count = 0;
	out.open("just_pq_type_ca_sim.htm");

	out << "<HTML><BODY><TABLE>";

	for (i = 1; i <= 15; i++)
	{
		ClearVisitedFlagForAllMolecules();
		
		count = 0;
		
		//Search for glutame molecule
		startNode = GetNodeBasedOnName("PQ_Type_Ca");

		count = ExpandSim(startNode, i, count);

		out << "<TR><TD>" << count << "</TD></TR>";
		
	}

	out << "</TABLE></BODY></HTML>";

	out.close();
}

void SimulateAllLigands(void)
{
	MOLECULE* startNode;
	int i, k;
	ofstream out;
	int count = 0;
	char fileName[100];
	char pajekFileName[100];


	out.open("all_ligands_sim.htm");

	out << "<HTML><BODY><TABLE>";
//	machines << "<HTML><BODY>";

	startNode = MoleculesList;

	k = 0;

	while (startNode)
	{
		if (!strcmp(startNode->moleculeType, "Ligand"))
		{
			k++;

			out << "<TR><TD>" << startNode->name << "</TD>";
			
			ClearVisitedFlagForAllMolecules();

			for (i = 1; i <= 15; i++)
			{	
				
				count = 0;

				count = ExpandSim(startNode, i, count);
				count = CountAllVisited();
				
				sprintf(fileName, "%s_sub_net_depth%d.sig", startNode->name, i);
				sprintf(pajekFileName, "depth_networks%d.net", i);
				startNode->visited = 1;
				
				DumpAllVisited(fileName);
				DumpFlaggedInteractionsToPajek(pajekFileName);				
				
				out << "<TD>" << count << "</TD>";
			}

			
			out << "</TR>" << endl;

		}

		startNode = startNode->next;
	}

	out << "</TABLE></BODY></HTML>";
	out.close();
}
	
void SimulateAllTFs(void)
{
	MOLECULE* startNode;
	int i, k;
	ofstream out;
	int count = 0;
	char fileName[100];



	out.open("all_TFs_sim.htm");

	out << "<HTML><BODY><TABLE>";
//	machines << "<HTML><BODY>";

	startNode = MoleculesList;

	k = 0;

	while (startNode)
	{
		if (!strcmp(startNode->moleculeType, "TF"))
		{
			k++;

			out << "<TR><TD>" << startNode->name << "</TD>";
			
			ClearVisitedFlagForAllMolecules();

			for (i = 1; i <= 15; i++)
			{	
				
				count = 0;

				count = ExpandReverseSim(startNode, i, count);
				count = CountAllVisited();
				
				sprintf(fileName, "%s_sub_net_depth%d.sig", startNode->name, i);

				startNode->visited = 1;
				
				DumpAllVisited(fileName);
				
				out << "<TD>" << count << "</TD>";
			}

			
			out << "</TR>" << endl;

		}

		startNode = startNode->next;
	}

	out << "</TABLE></BODY></HTML>";
	out.close();
}

void SimulateArp23AndAMPAR(void)
{
	MOLECULE* startNode;
	int i, k;
	ofstream out;
	int count = 0;
	char fileName[100];



	out.open("ARP23_AND_AMPA_sim.htm");

	out << "<HTML><BODY><TABLE>";
//	machines << "<HTML><BODY>";

	startNode = MoleculesList;

	k = 0;

	while (startNode)
	{
		if ((!strcmp(startNode->name, "GLUR1")) || (!strcmp(startNode->name, "ARP23")))
		{
			k++;

			out << "<TR><TD>" << startNode->name << "</TD>";
			
			ClearVisitedFlagForAllMolecules();

			for (i = 1; i <= 15; i++)
			{	
				
				count = 0;

				count = ExpandReverseSim(startNode, i, count);
				count = CountAllVisited();
				
				sprintf(fileName, "%s_sub_net_depth%d.sig", startNode->name, i);

				startNode->visited = 1;
				
				DumpAllVisited(fileName);
				
				out << "<TD>" << count << "</TD>";
			}

			
			out << "</TR>" << endl;

		}

		startNode = startNode->next;
	}

	out << "</TABLE></BODY></HTML>";
	out.close();
}

void SimulateLigandPairs(char* name1, char* name2)
{
	MOLECULE* startNode;
	MOLECULE* startNode2;
	int i;
	char fileName[100];

	startNode = MoleculesList;

	while (startNode)
	{
		if (!strcmp(startNode->name, name1))
		{
			break;
		}
		startNode = startNode->next;
	}

	startNode2 = MoleculesList;

	while (startNode2)
	{
		if (!strcmp(startNode2->name, name2))
		{
			break;
		}
		startNode2 = startNode2->next;
	}		
	
	for (i = 1; i <= 15; i++)
	{
		ClearVisitedFlagForAllMolecules();

		ExpandSim(startNode, i, 0);
		ExpandSim(startNode2, i, 0);
		sprintf(fileName, "%s_and_%s_sub_net_depth%d.sig", startNode->name, startNode2->name, i);

		startNode->visited = 1;
		startNode2->visited = 1;

		DumpAllVisited(fileName);
	}
}

void SimulateAllAtOnce(void)
{
	MOLECULE* startNode;
	int l;
	ofstream out;
	char fileName[100];
	int count = 0;

	out.open("all_ligands_at_once.htm");

	out << "<HTML><BODY><TABLE><TR>";

	for (l = 1; l <= 15; l++)
	{
		startNode = MoleculesList;
		count = 0;
        ClearVisitedFlagForAllMolecules();
		while (startNode)
		{
			if (!strcmp(startNode->moleculeType, "Ligand"))
		    {
				count = ExpandSim(startNode, l, count);
				startNode->visited = 1;
			}
			startNode = startNode->next;
		}
		sprintf(fileName, "ALL_AT_ONCE_sub_net_depth%d.sig", l);

		
				
		DumpAllVisited(fileName);
		out << "<TD>" << count << "</TD>";
	}
	out << "</TR></BODY></HTML>" << endl;
	out.close();
}
	

void SimulateAch(void)
{
	MOLECULE* startNode;
	int i;
	ofstream out;
	int count = 0;
	out.open("just_ach_sim.htm");

	out << "<HTML><BODY><TABLE>";

	for (i = 1; i <= 15; i++)
	{
		ClearVisitedFlagForAllMolecules();
		
		count = 0;
		
		//Search for glutame molecule
		startNode = GetNodeBasedOnName("Ach");

		count = ExpandSim(startNode, i, count);

		out << "<TR><TD>" << count << "</TD></TR>";
		
	}

	out << "</TABLE></BODY></HTML>";

	out.close();
}

void SimulateGlutamate(void)
{
	MOLECULE* startNode;
	int i;
	ofstream out;
	int count = 0;
	char fileName[100];
	out.open("just_glutamate_sim.htm");

	out << "<HTML><BODY><TABLE>";

	for (i = 1; i <= 15; i++)
	{
		ClearVisitedFlagForAllMolecules();
		
		count = 0;
		
		//Search for glutame molecule
		startNode = GetNodeBasedOnName("GLUTAMATE");

		count = ExpandSim(startNode, i, count);

		sprintf(fileName, "glutamate_sub_net_depth%d.sig", i);

		startNode = GetNodeBasedOnName("GLUTAMATE");

		startNode->visited = 1;

		DumpAllVisited(fileName);

		out << "<TR><TD>" << count << "</TD></TR>";
		
	}

	out << "</TABLE></BODY></HTML>";

	out.close();
}

void SimulateNE(void)
{
	MOLECULE* startNode;
	int i;
	ofstream out;
	int count = 0;

	out.open("just_ne_sim.htm");

	out << "<HTML><BODY><TABLE>";

	for (i = 1; i <= 15; i++)
	{
		ClearVisitedFlagForAllMolecules();
		
		count = 0;
		
		//Search for glutame molecule
		startNode = GetNodeBasedOnName("NE");

		count = ExpandSim(startNode, i, count);

		out << "<TR><TD>" << count << "</TD></TR>";

	}

	out << "</TABLE></BODY></HTML>";

	out.close();
}

void SimulateBothGlutamateAndNE(void)
{
	MOLECULE* startNode;
	int i, j;
	ofstream out;
	int count = 0;

	out.open("glutamate_and_ne_sim.htm");

	out << "<HTML><BODY><TABLE>";

	for (j = 1; j <= 15; j++)
	{
		out << "<TR>";
		for (i = 1; i <= 15; i++)
		{
			ClearVisitedFlagForAllMolecules();
			ClearGlutamateVisitedFlagForAllMolecules();
			count = 0;
		
			//Search for the glutame molecule
			startNode = GetNodeBasedOnName("Glutamate");

			count = ExpandSim(startNode, i, count);

			ClearVisitedFlagForAllMolecules();

			//Search for the ne molecule
			startNode = GetNodeBasedOnName("NE");

			count = ExpandSimAfterGlu(startNode, j, count);

			out << "<TD>" << count << "</TD>";
		}
		out << "</TR>";
	}

	out << "</TABLE></BODY></HTML>";

	out.close();
}

int ExpandSim (MOLECULE* tempNode, int depth, int count)
{
	MOLECULE* tempNode1;
	int i;
	
	tempNode->visited = depth;

	if (depth == 0)
	{
		return count;
	}

	for (i = 0; i < tempNode->linksCount; i++)
	{
		tempNode1 = GetNodeBasedOnNumber(tempNode->linksTo[i]);

		if (((tempNode1->visited == 0) || (tempNode1->visited < depth)) && (DirectionOK(tempNode, tempNode1)))
		{
			// do not increment count if already activated by the glu search
			count = ExpandSim(tempNode1, depth - 1, count + 1);
		}
	}
	return count;
}

int ExpandReverseSim (MOLECULE* tempNode, int depth, int count)
{
	MOLECULE* tempNode1;
	int i;
	
	tempNode->visited = depth;

	if (depth == 0)
	{
		return count;
	}


	for (i = 0; i < tempNode->linksCount; i++)
	{
		tempNode1 = GetNodeBasedOnNumber(tempNode->linksTo[i]);
		
		if (((tempNode1->visited == 0) || (depth > tempNode1->visited)) && (OppositeDirectionOKWithNeutralLinks(tempNode, tempNode1)))
		{
			//tempNode1->visited = depth;
			// do not increment count if already activated by the glu search
			count = ExpandReverseSim(tempNode1, depth - 1, count + 1);
		}
	}
	return count;
}

int ExpandSimAfterGlu (MOLECULE* tempNode, int depth, int count)
{
	MOLECULE* tempNode1;
	int i;

	if (depth == 0)
	{
		return count;
	}

	for (i = 0; i < tempNode->linksCount; i++)
	{
		tempNode1 = GetNodeBasedOnNumber(tempNode->linksTo[i]);
		
		if (((tempNode1->visited == 0) || (depth > tempNode1->visited)) && (DirectionOK(tempNode, tempNode1)))
		{
			if ((tempNode1->visitedGlu) || (tempNode1->visited))
			{
				tempNode1->visited = depth;
				count = ExpandSimAfterGlu(tempNode1, depth - 1, count);
			}
			else
			{
				tempNode1->visited = depth;
				count = ExpandSimAfterGlu(tempNode1, depth - 1, count + 1);
			}
		}
	}
	return count;
}

void ClearVisitedFlagForAllMolecules(void)
{
	MOLECULE* tempNode;

	tempNode = MoleculesList;

	while (tempNode)
	{
		tempNode->visited = 0;
		tempNode->visited2 = 0;
		tempNode = tempNode->next;
	}

	return;

	return;
}

void ClearGlutamateVisitedFlagForAllMolecules(void)
{
	MOLECULE* tempNode;

	tempNode = MoleculesList;

	while (tempNode)
	{
		tempNode->visitedGlu = 0;
		tempNode = tempNode->next;
	}

	return;
}

void CTestSVGDlg::OnButtonFindBidirect() 
{

}

void CTestSVGDlg::OnButtonPathToNucleus() 
{

}

int ExpandNucleusSearch (MOLECULE* tempNode, int depth, int count)
{
	MOLECULE* tempNode1;
	int i;

	if (!strcmp(tempNode->location, "Nucleus"))
	{
		return 1;
	}
	for (i = 0; i < tempNode->linksCount; i++)
	{
		tempNode1 = GetNodeBasedOnNumber(tempNode->linksTo[i]);
		
		if (!strcmp(tempNode1->location, "Nucleus"))
		{
			return 1;
		}
		
		if (((tempNode1->visited == 0) && (depth > tempNode1->visited)) && (DirectionOK(tempNode, tempNode1)))
		{
			tempNode1->visited = depth;
			count = ExpandNucleusSearch(tempNode1, depth - 1, count);	
		}
	}
	return count;
}

void CTestSVGDlg::OnButtonList() 
{
	ofstream out;
	MOLECULE* tempNode;

	ComputeCC();
	ComputeAvgPathLength();

	tempNode = MoleculesList;

	out.open("list.txt");

	while (tempNode)
	{
		if (tempNode->linksCount > 22)
		{
			out << tempNode->name << " " << tempNode->linksCount << " " << tempNode->cc << " " << tempNode->avgPathLength << endl;
		}

		tempNode = tempNode->next;

	}

	out.close();

	AfxMessageBox("Done12!");

	return;	
}


void CTestSVGDlg::OnButtonDetailedList() 
{
	ofstream out;
	MOLECULE* tempNode;

	tempNode = MoleculesList;

	out.open("detailed_list.txt");

	while (tempNode)
	{

		out << tempNode->name << " " << tempNode->moleculeType << " " << tempNode->location << " " << endl;

		tempNode = tempNode->next;

	}

	out.close();

	AfxMessageBox("Done13!");

	return;		
}

void CTestSVGDlg::OnButtonCountFeedBackLoops() 
{
	MOLECULE* tempNode;

	CountDirectedCycles(3, 0);
	ofstream out;

	out.open("times_feedback_loops.htm");

	out << "<html><body><table>";

	tempNode = MoleculesList;
	
	while (tempNode)
	{
		out << "<tr><td>" << tempNode->name << "</td><td>" << tempNode->appearInFeedbackLoops << "</td></tr>" << endl;
		tempNode = tempNode->next;
	}

	out << "</table></body></html>";
	
	out.close();

	AfxMessageBox("Done14!");
}

void CTestSVGDlg::OnButtonCountFeedforwardLoops() 
{
	MOLECULE* tempNode;

	CountConvergedCycles(3, 0);

	ofstream out;

	out.open("times_feedforward_loops.htm");

	out << "<html><body><table>";

	tempNode = MoleculesList;
	
	while (tempNode)
	{
		out << "<tr><td>" << tempNode->name << "</td><td>" << tempNode->appearInFeedforwardLoops << "</td></tr>" << endl;
		tempNode = tempNode->next;
	}

	out << "</table></body></html>";
	
	out.close();

	AfxMessageBox("Done15!");
	
}

void CTestSVGDlg::OnButtonDistanceToMachines() 
{
	
}

void LoadMachines(void)
{
	ifstream machines;
	ofstream debugMachines;;
	char name[100];
	int machine;
	MOLECULE* tempNode;

	debugMachines.open("machines_debug.txt");

	machines.open("machines.txt");

	while (!machines.eof())
	{
		machines >> name;
		machines >> machine;

		tempNode = MoleculesList;

		while (tempNode)
		{
			if (!strcmp(tempNode->name, name))
			{
				tempNode->machine = machine;
				break;
			}
			tempNode = tempNode->next;
		}
		
		if (!tempNode)
		{
			debugMachines << name << " " << machine << endl;
		}
	}

	debugMachines << endl << endl;

	tempNode = MoleculesList;

	while (tempNode)
	{
		debugMachines << tempNode->name << " " << tempNode->machine << endl;
		tempNode = tempNode->next;
	}

	debugMachines.close();
	machines.close();
}

void LoadAccessions(void)
{
	ifstream accessions;
	int strongHomologs;
	int weakHomologs;
	char name[100];
	char accession[100];
	MOLECULE* tempNode;

	tempNode = MoleculesList;

	while (tempNode)
	{
		strcpy(tempNode->accHuman, "NA");
		strcpy(tempNode->accMouse, "NA");
		tempNode->strongHomologs = 0;
		tempNode->weakHomologs = 0;
		tempNode = tempNode->next;
	}

	accessions.open("accessions.txt");

	while (!accessions.eof())
	{
		accessions >> name;
		accessions >> strongHomologs;
		accessions >> weakHomologs;
		accessions >> accession;
		
		tempNode = MoleculesList;

		while (tempNode)
		{
			if (!strcmp(tempNode->name, name))
			{
				strcpy(tempNode->accHuman, accession);
				strcpy(tempNode->accMouse, accession);
				tempNode->strongHomologs = strongHomologs;
				tempNode->weakHomologs = weakHomologs;
				break;
			}
			tempNode = tempNode->next;
		}
	}
	accessions.close();
}
void CTestSVGDlg::OnButtonMapBasedOnMachines() 
{
	LoadMachines();

	ifstream connections;
    ofstream graph;
	MOLECULE* tempNode;
	MOLECULE* tempNode1;
	INTERACTION* tempInteraction;    
	graph.open("machines.net");
	char colorAndShape[100];
	char moleculeTypeIndex;
    
	//TakeOutTheHubs();
	
	graph << "*Vertices    " << NumberOfMolecules << endl;


	tempNode = MoleculesList;


	while (tempNode)
	{
		moleculeTypeIndex = GetMoleculeTypeIndex(tempNode->moleculeType);

		GetColorAndShape(moleculeTypeIndex, colorAndShape);

		if (tempNode->machine == TRANSMEMBRANE)
		{
			graph << tempNode->number << "  " << "\"" << tempNode->name << "\"" << "ic Orange ellipse" << endl;
		}
		else if (tempNode->machine == TRANSMISSION)
		{
			graph << tempNode->number << "  " << "\"" << tempNode->name << "\"" << " ic Goldenrod ellipse" << endl;
		}
		else if (tempNode->machine == TRANSLATION)
		{
			graph << tempNode->number << "  " << "\"" << tempNode->name << "\"" << " ic SkyBlue ellipse" << endl;
		}
		else if (tempNode->machine == TRANSCRIPTION)
		{
			graph << tempNode->number << "  " << "\"" << tempNode->name << "\"" << " ic LightGreen ellipse" << endl;
		}
		else if (tempNode->machine == SECRETION)
		{
			graph << tempNode->number << "  " << "\"" << tempNode->name << "\"" << " ic Orchid ellipse" << endl;
		}
		else if (tempNode->machine == CYTOSKELETON)
		{
			graph << tempNode->number << "  " << "\"" << tempNode->name << "\"" << " ic Periwinkle ellipse" << endl;
		}
		else if (tempNode->machine == APOPTOSIS)
		{
			graph << tempNode->number << "  " << "\"" << tempNode->name << "\"" << " ic Black ellipse" << endl;
		}
		else if (tempNode->machine == EXTRACELLULAR_LIGANDS)
		{
			graph << tempNode->number << "  " << "\"" << tempNode->name << "\"" << " ic White ellipse" << endl;
		}
		else
		{
			graph << tempNode->number << "  " << "\"" << tempNode->name << "\"" << " ic Orange ellipse" << endl;
		}

		
		tempNode = tempNode->next;
	}


	graph << "*Arcs" << endl;

	tempInteraction = InteractionsList;

	while (tempInteraction)
    { 
	    tempNode = GetNodeBasedOnName(tempInteraction->source);
		tempNode1 = GetNodeBasedOnName(tempInteraction->target);

		//if ((tempNode->linksCount <= 15) && (tempNode1->linksCount <= 15))
		//{
		if (!strcmp(tempInteraction->effect, "+"))
		{
			graph << "   " << GetNumberBasedOnString(tempInteraction->source) << "    ";
			graph << GetNumberBasedOnString(tempInteraction->target) << "    " <<  "1 c Green" << endl;
			graph << "   " << GetNumberBasedOnString(tempInteraction->source) << "    ";
			graph << GetNumberBasedOnString(tempInteraction->target) << "    " <<  "1 c Green" << endl;
		}
		else if (!strcmp(tempInteraction->effect, "_"))
		{
			graph << "   " << GetNumberBasedOnString(tempInteraction->source) << "    ";
			graph << GetNumberBasedOnString(tempInteraction->target) << "    " <<  "1 c Orange" << endl;
			graph << "   " << GetNumberBasedOnString(tempInteraction->source) << "    ";
			graph << GetNumberBasedOnString(tempInteraction->target) << "    " <<  "1 c Orange" << endl;
		} 
		else 	if (!strcmp(tempInteraction->effect, "0"))
		{
			graph << "   " << GetNumberBasedOnString(tempInteraction->source) << "    ";
			graph << GetNumberBasedOnString(tempInteraction->target) << "    " <<  "1 c Blue" << endl;
		}
		
		//}

		tempInteraction = tempInteraction->next;
    }
	
	graph.close();

	AfxMessageBox("Done16!");
    return;	
	
}

void CTestSVGDlg::OnBnClickedButtonDiffMaps()
{

}

bool IsNodeInListToDraw(MOLECULE* node)
{
	MOLECULE* tempNode;

	tempNode = ListToDraw;

	while (tempNode)
	{
		if (!strcmp(tempNode->name, node->name))
		{
			return true;
		}
	    tempNode = tempNode->next;
	}

	return false;
}

void AddToListToDraw(MOLECULE* tempNode)
{
	MOLECULE* tempNode2;
	MOLECULE* tempNode3;
	int count = 1;

	if (!IsNodeInListToDraw(tempNode))
	{	
		tempNode2 = ListToDraw;
		tempNode3 = tempNode2;
		while (tempNode2)
		{
			count++;	
			tempNode3 = tempNode2;
			tempNode2 = tempNode2->next;
		}
		tempNode2 = (MOLECULE*) malloc(sizeof(MOLECULE));
		memcpy(tempNode2, tempNode, sizeof(MOLECULE));
		tempNode2->next = 0;
		tempNode2->number = count;
		if (!tempNode3)
		{
			ListToDraw = tempNode2;
		}
		else
		{
			tempNode3->next = tempNode2;
		}
	}
}
void CTestSVGDlg::OnBnClickedButtonMachineCount()
{
	MOLECULE* tempNode;	
	ofstream out;
	int countToTranscription = 0;
	int countToCentral = 0;
	int countToCytoskeleton = 0;
	int countToTranslation = 0;
	int countToTransmission = 0;
	int countToVesicles = 0;
	int countToApoptosis = 0;
	int countMembrane = 0;
    int other = 0;
	int input = 0;
	int total = 0;
	//LoadMachines();
	
	out.open("machines_counts.htm");

	out << "<html><body><table>";

	tempNode = MoleculesList;
	
	while (tempNode)
	{
		if ((!strcmp(tempNode->location, "ER")) || (!strcmp(tempNode->location, "Ribosomes")))
		{
			tempNode->machine = TRANSLATION;
			countToTranslation++;
		}
		else if (!strcmp(tempNode->moleculeType, "Channel"))
		{
			tempNode->machine = TRANSMISSION;
			countToTransmission++;
		}
		else if (!strcmp(tempNode->location, "Vesicles"))
		{
			tempNode->machine = SECRETION;
			countToVesicles++;
		}
		else if (!strcmp(tempNode->moleculeType, "Cytoskeleton"))
		{
			tempNode->machine = CYTOSKELETON;
			countToCytoskeleton++;
		}
		else if (!strcmp(tempNode->location, "Nucleus"))
		{
			tempNode->machine = TRANSCRIPTION;
			countToTranscription++;
		}
		else if ((!strcmp(tempNode->location, "Mitochondria")) || (!strcmp(tempNode->moleculeType, "Protease")))
		{
			tempNode->machine = APOPTOSIS;
			countToApoptosis++;
		}
		else if (!strcmp(tempNode->moleculeType, "Ligand"))
		{
			tempNode->machine = EXTRACELLULAR_LIGANDS;
			 input++;
		}
		else if (!strcmp(tempNode->location, "Membrane"))
		{
			tempNode->machine = TRANSMEMBRANE;
			countMembrane++;
		}
		else
		{
			tempNode->machine = CENTRAL_SIGNALING;
			countToCentral++;
		}
		tempNode = tempNode->next;
	}

	out << "Central Signaling: " << countToCentral << "<br>" << endl;
	out << "Ion Channels: " << countToTransmission << "<br>" << endl;
	out << "Vesicles: " << countToVesicles << "<br>" << endl;
	out << "Cytoskeleton: " << countToCytoskeleton << "<br>" << endl;
	out << "Nucleus: " << countToTranscription << "<br>" << endl;
	out << "Mitochondria: " << countToApoptosis << "<br>" << endl;
	out << "Ribosomes and ER: " << countToTranslation << "<br>" << endl;
	out << "Ligands: " << input << "<br>" << endl;
    out << "Trans-Membrane: " << countMembrane << "<br>" << endl;
 
	out << "</body></html>";
	
	out.close();

	AfxMessageBox("Done17!");
}

void CTestSVGDlg::OnBnClickedButton12()
{
	
}

void CTestSVGDlg::OnBnClickedButtonDumpMachinesAndAccessions()
{
	
}

void CTestSVGDlg::OnBnClickedButton11()
{
	MOLECULE* tempNode;
	ofstream out;
	
	SortMoleculeList();
	LoadMachines();
	LoadAccessions();
	
	out.open("machines_and_accessions.htm");
	out << "<html><body><table>";

	tempNode = MoleculesList;

	while (tempNode)
	{
		out << "<tr><td>" << tempNode->name << "</td><td>" << tempNode->machine << "</td><td>" << tempNode->accHuman << "</td><td>" << tempNode->strongHomologs << "</td><td>" << tempNode->weakHomologs << "</td></tr>" << endl;
		tempNode = tempNode->next;
	}

	out << "</table></body></html>";

	out.close();

	AfxMessageBox("Done18!");
}

void CTestSVGDlg::OnBnClickedButton13()
{
	SimulateCREB();
	AfxMessageBox("Done19!");
}

void CTestSVGDlg::OnBnClickedButtonProgressReport()
{
	
	AfxMessageBox("Done20!");
}

void CTestSVGDlg::OnBnClickedButton14()
{
	
	AfxMessageBox("Done21!");
}

void CTestSVGDlg::OnBnClickedButton15()
{	
	MOLECULE* tempNode;
	INTERACTION* tempInt;
	int numberOfIslands = 0;
	int listSoFar[8000];
	int listSoFarIndex = 0;
	int islandSizes[1000];
	int previousIndex = 1;
	int islands = 0;
	int largest = 0;
	int ok, i;

	tempNode = MoleculesList;

	while (tempNode)
	{
		previousIndex = listSoFarIndex;
	    listSoFarIndex = ExpandIsland(tempNode, listSoFar, listSoFarIndex);
		
		if (previousIndex != listSoFarIndex)
		{
		    islandSizes[islands] = listSoFarIndex - previousIndex; 
		    islands++;
		}
		tempNode = tempNode->next;
	}
	
	for (i = 0; i < islands; i++)
	{
		if (islandSizes[i] > largest)
		{
			largest = islandSizes[i];
		}
	}

	tempNode = MoleculesList;
	islands = 0;
	listSoFarIndex = 0;
	while (tempNode)
	{
		previousIndex = listSoFarIndex;
	    listSoFarIndex = ExpandIsland(tempNode, listSoFar, listSoFarIndex);
		
		if (previousIndex != listSoFarIndex)
		{
		    islandSizes[islands] = listSoFarIndex - previousIndex;
			if (largest == islandSizes[islands])
			{
				break;
			}
		    islands++;
		}
		tempNode = tempNode->next;
	}

	ofstream out;

	CFileDialog myDialog(FALSE, NULL, "*.sig", OFN_OVERWRITEPROMPT, NULL, NULL );

	myDialog.DoModal();
	
	out.open(myDialog.m_ofn.lpstrFile);

	tempInt = InteractionsList;

	while (tempInt)
	{
		ok = 0;
		for (i = 0; i < largest; i++)
		{
			tempNode = GetNodeBasedOnNumber(listSoFar[i]);

			if ((!strcmp(tempNode->name, tempInt->source)) || (!strcmp(tempNode->name, tempInt->target)))
			{
				ok = 1;
				break;
			}
		}

		if (ok)
		{
			out << tempInt->source << " " << tempInt->sourceAccHuman << " " << tempInt->sourceAccMouse << " " << tempInt->sourceType  << " " << tempInt->sourceLocation  << " " << tempInt->target  << " " << tempInt->targetAccHuman  << " " << tempInt->targetAccMouse  << " " << tempInt->targetType  << " " << tempInt->targetLocation  << " " << tempInt->effect  << " " << tempInt->typeOfInteraction << " " << tempInt->pmid << endl;
	
		}
		tempInt = tempInt->next;
	}
	
	out.close();

	MessageBox("Done!", "Dumping the big component", MB_OK | MB_ICONINFORMATION);

	return; 	
}

void CTestSVGDlg::OnBnClickedButtonIndexInteractions()
{
	ofstream out;
	INTERACTION* tempNode;

	out.open("index.htm");

	out << "<html><body>";

	out << "List of interactions<br>";
	
	tempNode = InteractionsList;

	out << "<table><tr><b><td>Source</td><td>Target</td><td>Effect</td><td>Interaction Type</td></tr></b>" << endl;
	
	while (tempNode)
	{
		out << "<tr><td><a href=\"";
		out << tempNode->source << ".htm\">";
		out << tempNode->source << "</a>";
		out << "</td><td><a href=\"";
		out << tempNode->target << ".htm\">";
		out << tempNode->target << "</a>";
		
		if (!strcmp(tempNode->effect, "+"))
		{
			out << "</td><td><font color=green>";

			out << " + ";
		}
		else if (!strcmp(tempNode->effect, "_"))
		{
			out << "</td><td><font color=red>";

			out << " - ";
		}
		else
		{
			out << "</td><td><font color=blue>";

			out << " 0 ";
		}
		out << "</font></td><td>";
		out << tempNode->typeOfInteraction;
		out << "</td></tr>" << endl;
		tempNode = tempNode->next;
	}

	out << "</table></body></html>" << endl;

	out.close();

}

void CTestSVGDlg::OnStnClickedStaticProgress()
{
	// TODO: Add your control notification handler code here
}

void CTestSVGDlg::OnBnClickedButton17()
{
	MOLECULE* tempNode;
	ofstream out;
	ofstream out1;
	int negatives = 0;
	int positives = 0;
	int listSoFar[20];
	int i;
	char fileName[200];

	out.open("creb_pathways_count.htm");

	out << "<html><body><table>" << endl;
	out << "<tr><td>Name</td><td>Positives</td><td>Negatives</td><tr>" << endl;

	for (i = 5; i <= 5; i++)
	{
		tempNode = MoleculesList;

		while (tempNode)
		{
			if (!strcmp(tempNode->name, "GLUTAMATE"))
			{
				negatives = 0;
				positives = 0;
				listSoFar[0] = tempNode->number;
				strcpy(fileName, "to_AMPAR_");
				strcat(fileName, tempNode->name);
				strcat(fileName, ".sig");
				out1.open(fileName);
				ClearInteractionsFlag();
				IndexOfGlobalList = 0;
				CountNumberOfPathwaysToOutputAndDump(out1, "GLUR1", tempNode, i, 1, listSoFar, positives, negatives);
				AddInteractionsForFeedbackLoops(out1);
				out1.close();
				out << "<tr><td>" << tempNode->name << "</td><td>" << positives << "</td><td>" << negatives << "</td></tr>" << endl;
			}
			tempNode = tempNode->next;
		}
	}

	AfxMessageBox("Done22!");

}


void CountNumberOfPathwaysToOutput(char* targetName, MOLECULE* tempNode, int sizeWeLookFor, int howDeep, int* listSoFar, int &positives, int &negatives)
{
	MOLECULE* localNode;
	int i;
	localNode = tempNode;

	if ((howDeep <= sizeWeLookFor) && (!strcmp(tempNode->name, targetName)))
	{
		if (IsItNegativePathway(listSoFar, howDeep))
		{
			negatives++;
		}
		else
		{
			positives++;
		}
	}
	else if (howDeep > sizeWeLookFor)
	{
		return;
	}
	else
	{
		for (i = 0; i < tempNode->linksCount; i++)
		{	
			localNode = GetNodeBasedOnNumber(tempNode->linksTo[i]);

			if (NotAlreadyInList(listSoFar, howDeep, localNode->number) && (DirectionOK(tempNode, localNode)))
			{
				listSoFar[howDeep] = localNode->number;
				CountNumberOfPathwaysToOutput(targetName, localNode, sizeWeLookFor, howDeep + 1, listSoFar, positives, negatives);
			}
		}
	}	
}

void CountNumberOfPathwaysToOutputAndDump(ofstream &out1, char* targetName, MOLECULE* tempNode, int sizeWeLookFor, int howDeep, int* listSoFar, int &positives, int &negatives)
{
	MOLECULE* localNode;
	MOLECULE* tempNode3;
	MOLECULE* tempNode4;
	INTERACTION* tempInt;
	int i;
	localNode = tempNode;

	if ((howDeep <= sizeWeLookFor) && (!strcmp(tempNode->name, targetName)))
	{
		if (IsItNegativePathway(listSoFar, howDeep))
		{
			negatives++;
		}
		else
		{
			positives++;
		}
		AddToGlobalListOfSubNetwork(listSoFar, howDeep);
		for (i = 0; i < howDeep - 1; i++)
		{
				tempNode3 = GetNodeBasedOnNumber(listSoFar[i]);
				tempNode4 = GetNodeBasedOnNumber(listSoFar[i + 1]);
				tempInt = GetInteraction(tempNode3->name, tempNode4->name);
				if (!tempInt)
				{
					tempInt = GetInteraction(tempNode4->name, tempNode3->name);
				}
				if (!tempInt->flag)
				{
					out1 << tempInt->source << " " << tempInt->sourceAccHuman << " " << tempInt->sourceAccMouse << " " << tempInt->sourceLocation << " " << tempInt->sourceType << " " << tempInt->target << " " << tempInt->targetAccHuman << " " << tempInt->targetAccMouse << " " << tempInt->targetType << " " << tempInt->sourceLocation << " " << tempInt->effect << " " << tempInt->typeOfInteraction << " " << tempInt->pmid << endl;
				    tempInt->flag = 1;
				}
		}
	}
	else if (howDeep > sizeWeLookFor)
	{
		return;
	}
	else
	{
		for (i = 0; i < tempNode->linksCount; i++)
		{	
			localNode = GetNodeBasedOnNumber(tempNode->linksTo[i]);

			if (PathwayGeneratorSetupStruct.directOnly)
			{
				if (NotAlreadyInList(listSoFar, howDeep, localNode->number) && (DirectionOnlyOK(tempNode, localNode)))
				{
					listSoFar[howDeep] = localNode->number;
					CountNumberOfPathwaysToOutputAndDump(out1, targetName, localNode, sizeWeLookFor, howDeep + 1, listSoFar, positives, negatives);
				}
			}
			else
			{
				if (NotAlreadyInList(listSoFar, howDeep, localNode->number) && (DirectionOK(tempNode, localNode)))
				{
					listSoFar[howDeep] = localNode->number;
					CountNumberOfPathwaysToOutputAndDump(out1, targetName, localNode, sizeWeLookFor, howDeep + 1, listSoFar, positives, negatives);
				}
			}
		}
	}	
}

void MarkAllNodesToOutput(char* targetName, MOLECULE* tempNode, int sizeWeLookFor, int howDeep, int* listSoFar)
{
	MOLECULE* localNode;
	MOLECULE* tempNode3;
	MOLECULE* tempNode4;
	INTERACTION* tempInt;
	int i;

	localNode = tempNode;

	if ((howDeep <= sizeWeLookFor) && (!strcmp(tempNode->name, targetName)))
	{
		for (i = 0; i < howDeep - 1; i++)
		{
				tempNode3 = GetNodeBasedOnNumber(listSoFar[i]);
				tempNode4 = GetNodeBasedOnNumber(listSoFar[i + 1]);
				tempInt = GetInteraction(tempNode3->name, tempNode4->name);
				if (!tempInt)
				{
					tempInt = GetInteraction(tempNode4->name, tempNode3->name);
				}
				if (!tempInt->flag)
				{
					tempNode3->visited = 1;
					tempNode4->visited = 1;
				    tempInt->flag = 1;
				}
		}
	}
	else if (howDeep > sizeWeLookFor)
	{
		return;
	}
	else
	{
		for (i = 0; i < tempNode->linksCount; i++)
		{	
			localNode = GetNodeBasedOnNumber(tempNode->linksTo[i]);

			if (NotAlreadyInList(listSoFar, howDeep, localNode->number) && (DirectionOK(tempNode, localNode)))
			{
				listSoFar[howDeep] = localNode->number;
				MarkAllNodesToOutput(targetName, localNode, sizeWeLookFor, howDeep + 1, listSoFar);
			}
		}
	}	
}

void AddToGlobalListOfSubNetwork(int* listSoFar, int howDeep)
{
	int i, j, alreadyThere;

	for (i = 0; i < howDeep - 1; i++)
	{
		alreadyThere = 0;
		for (j = 0; j < IndexOfGlobalList; j++)
		{
			if (GlobalList[j] == listSoFar[i])
			{
				alreadyThere = 1;
				break;
			}
		}

		if (!alreadyThere)
		{
			GlobalList[IndexOfGlobalList] = listSoFar[i];
			IndexOfGlobalList++;
		}
	}
}
void AddInteractionsForFeedbackLoops(ofstream &out1)
{
	int i, j;
	MOLECULE* tempNode1;
	MOLECULE* tempNode2;
	INTERACTION* tempInt;

	for (i = 0; i < IndexOfGlobalList; i++)
	{
		for (j = 0; j < IndexOfGlobalList; j++)
		{
			if (i != j)
			{
				tempNode1 = GetNodeBasedOnNumber(GlobalList[i]);
				tempNode2 = GetNodeBasedOnNumber(GlobalList[j]);
				tempInt = GetInteraction(tempNode1->name, tempNode2->name);
				if (!tempInt)
				{
					tempInt = GetInteraction(tempNode2->name, tempNode1->name);
				}
				if (tempInt)
				{
					if (!tempInt->flag)
					{
						out1 << tempInt->source << " " << tempInt->sourceAccHuman << " " << tempInt->sourceAccMouse << " " << tempInt->sourceLocation << " " << tempInt->sourceType << " " << tempInt->target << " " << tempInt->targetAccHuman << " " << tempInt->targetAccMouse << " " << tempInt->targetType << " " << tempInt->sourceLocation << " " << tempInt->effect << " " << tempInt->typeOfInteraction << " " << tempInt->pmid << endl;
						tempInt->flag = 1;
					}
				}
			}
		}
	}
}

void MarkInteractionsInBetween(void)
{
	int i, j;
	MOLECULE* tempNode1;
	MOLECULE* tempNode2;
	INTERACTION* tempInt;

	tempNode1 = MoleculesList;
	
	i = 0;
	while (tempNode1)
	{
		tempNode2 = MoleculesList;
		j = 0;
		while (tempNode2)
		{
			if (i != j)
			{
				tempInt = GetInteraction(tempNode1->name, tempNode2->name);
				if (!tempInt)
				{
					tempInt = GetInteraction(tempNode2->name, tempNode1->name);
				}
				if (tempInt)
				{
					if (!tempInt->flag)
					{
						tempInt->flag = 1;
					}
				}
			}
			j++;
			tempNode2 = tempNode2->next;	
		}
		i++;
		tempNode1 = tempNode1->next;
	}
}
void CTestSVGDlg::OnBnClickedButton18()
{
	int motifs31;
	int motifs32;
	int motifs41;
	int motifs42;
	int motifs51;

	//CountConvergedCycles();
	CountDirectedCycles(3, 0);
	

	ofstream out;

	out.open("motifs.htm");

	out << "<html><body><table>";

	//out << "<tr><td>" << NumberOfInteractions << "</td><td>" << NumberOfMolecules << "</td><td>" << PositiveFeedbackLoops[5] << "</td><td>" << NegativeFeedbackLoops[5] << "</td><td>" << PositiveConvergedCycles[5] << "</td><td>" << Gates[5] << "</td><td>" << PositiveFeedbackLoops[4] << "</td><td>" << NegativeFeedbackLoops[4] << "</td><td>" << PositiveConvergedCycles[4] << "</td><td>" << Gates[4] << "</td></tr>" << endl;

	motifs31 = CountMotif31();
	motifs32 = CountMotif32();
	motifs41 = CountMotif41();
	motifs42 = CountMotif42();
	motifs51 = CountMotif51();
		
	if (CountIslands() == 1)
	{
		out << "<tr><td>" << NumberOfInteractions << "</td><td>" << NumberOfMolecules << "</td><td>" << ComputeCC() << "</td><td>" << ComputeAvgPathLength() << "</td><td>" << CountIslands() << "</td><td>" << motifs31 << "</td><td>" << motifs32 << "</td><td>" << motifs41 << "</td><td>" << motifs42 <<  "</td><td>" << motifs51 << "</td></tr>" << endl;
	}
	else
	{
		out << "<tr><td>" << NumberOfInteractions << "</td><td>" << NumberOfMolecules << "</td><td>" << ComputeCC() << "</td><td>" << "NA" << "</td><td>" << CountIslands() << "</td><td>" << motifs31 << "</td><td>" << motifs32 << "</td><td>" << motifs41 << "</td><td>" << motifs42 <<  "</td><td>" << motifs51 << "</td></tr>" << endl;
	}
	out << "</table></body></html>";
	
	out.close();

	DumpMotif4List();
	SortMotif3List();
	SortMotif4List();
	SortMotif5List();
	DumpMotif3List();
	DumpMotif4List();
	DumpMotif5List();
	
	//DumpToJpegTopMotif3();
	//DumpToJpegTopMotif4();
	//DumpToJpegTopMotif5();

	AfxMessageBox("Done23!");
}

void ClearInteractionsFlag(void)
{
	INTERACTION* tempInt;
	tempInt = InteractionsList;
	while(tempInt)
	{
		tempInt->flag = 0;
		tempInt = tempInt->next;
	}
	return;
}


void CTestSVGDlg::OnBnClickedButton19()
{
	unsigned int i;
	int firstSlash;
	char fileNameStr[1000];
	char messageText[1000];
	int ret;

	//if (NumberOfMolecules > 100)
	//{
	//	MessageBox("This function only works for networks with less than 100 nodes!", "Problem!", MB_OK | MB_ICONINFORMATION); 
	
	//	return;
	//}

	CFileDialog myDialog(FALSE, NULL, "*.svg", OFN_OVERWRITEPROMPT, NULL, NULL );
	
	ret = myDialog.DoModal();

	if (ret == IDCANCEL)
	{
		return;
	}
	
	CString fileName = myDialog.m_ofn.lpstrFile;

	firstSlash = fileName.ReverseFind('\\');

	for (i = firstSlash; i < strlen(myDialog.m_ofn.lpstrFile); i++)
	{
		if ((myDialog.m_ofn.lpstrFile[i] == '.') ||
			(myDialog.m_ofn.lpstrFile[i] == ' '))
		{
			break;
		}
		fileNameStr[i - firstSlash] = myDialog.m_ofn.lpstrFile[i];
	}

	fileNameStr[i - firstSlash] = 0;

	fileName = fileNameStr;
	fileName.Replace("\\", "");
	strcpy(fileNameStr, fileName);

	CString graphString;
	INTERACTION* tempInteractionNode;
	MOLECULE* tempNode;

	graphString = "digraph G {";
	graphString += "size=\"37.5,50\";";
	graphString += "concentrate=false;\n";
	//graphString += "rankdir=LR";


	graphString += " { ";
	tempNode = MoleculesList;
	while (tempNode)
	{
		graphString +=  tempNode->name;
		graphString += " [style=\"filled\", URL=\"";
		graphString +=	tempNode->name;
		graphString +=	".htm\"";
		
		graphString += " shape=\"";
		graphString += GetShape(tempNode->name);
		graphString += "\", color=\"";
		graphString += GetColor(tempNode->name);
		graphString += "\"];\n";
		tempNode = tempNode->next;		
	}
	
	graphString += " } \n";
	

	tempInteractionNode = InteractionsList;

	while (tempInteractionNode)
	{
		graphString +=  tempInteractionNode->source;
		graphString +=  " -> ";
		graphString +=  tempInteractionNode->target;
			
		if (!strcmp(tempInteractionNode->effect, "+"))
		{
			graphString += " [arrowhead=\"normal\", color=\"darkgreen\"] ";
		}
		else if (!strcmp(tempInteractionNode->effect, "_"))
		{
			graphString += " [arrowhead=\"tee\",arrowsize=\"3.0\", color=\"red1\"] ";
		}
		else if (!strcmp(tempInteractionNode->effect, "0"))
		{
			graphString += " [arrowhead=\"box\",arrowtail=\"box\", color=\"blue1\"] ";
		}
		graphString +=  ";";
		
		tempInteractionNode = tempInteractionNode->next;
	}

	graphString += "}";

	DumpToDot(graphString, fileNameStr);
	DumpStringToJPEG(graphString, fileNameStr);	
	DumpStringToSVG(graphString, fileNameStr, 0, 0);

	sprintf(messageText, "Done creating %s.svg, %s.dot and %s.jpg files!", fileNameStr, fileNameStr, fileNameStr);
	MessageBox(messageText, "Success!", MB_OK | MB_ICONINFORMATION); 

	strcat(fileNameStr, ".svg");

	StartViewer(fileNameStr);
	strcpy(LastViewerCall, fileNameStr);
}

void CTestSVGDlg::OnBnClickedButton20()
{
	int j;
	int motifs31;
	int motifs32;
	int motifs41;
	int motifs42;
	int motifs51;
	char fileName[100];
	int totalPositiveFeedback = 0;
	int totalNegativeFeedback = 0;
	int totalPositiveFeedforward = 0;
	int totalNegativeFeedforward = 0;

	ofstream out;
	out.open("motifs_for_reduced_networks.htm");
	out << "<html><body><table>";
	out << "<tr><td>" << "Network Max" << "</td><td>" << "NumberOfInteractions" << "</td><td>" << "NumberOfMolecules" << "</td><td>" << "ComputeCC" << "</td><td>" << "ComputeAvgPathLength" << "</td><td>" << "CountIslands" << "</td><td>" << "totalPositiveFeedback" << "</td><td>" << "totalNegativeFeedback" << "</td><td>" << "totalPositiveFeedforward" << "</td><td>" << "totalNegativeFeedforward" << "</td></tr>" << endl;
	FreeNetwork();

	for (j = 4; j < 60; j++)
	{
		sprintf(fileName, "reduced_net%d.sig", j);
		LoadNetwork(fileName);

		//CountConvergedCycles();
		CountDirectedCycles(3, 0);
		
		motifs31 = CountMotif31();
		motifs32 = CountMotif32();
		motifs41 = CountMotif41();
		motifs42 = CountMotif42();
		motifs51 = CountMotif51();
		
		if (CountIslands() == 1)
		{
			out << "<tr><td>" << j << "</td><td>" << NumberOfInteractions << "</td><td>" << NumberOfMolecules << "</td><td>" << ComputeCC() << "</td><td>" << ComputeAvgPathLength() << "</td><td>" << CountIslands() << "</td><td>" << motifs31 << "</td><td>" << motifs32 << "</td><td>" << motifs41 << "</td><td>" << motifs42 <<  "</td><td>" << motifs51 << "</td></tr>" << endl;
		}
		else
		{
			out << "<tr><td>" << j << "</td><td>" << NumberOfInteractions << "</td><td>" << NumberOfMolecules << "</td><td>" << ComputeCC() << "</td><td>" << "NA" << "</td><td>" << CountIslands() << "</td><td>" << motifs31 << "</td><td>" << motifs32 << "</td><td>" << motifs41 << "</td><td>" << motifs42 <<  "</td><td>" << motifs51 << "</td></tr>" << endl;
		}

		FreeMotifs();
		FreeNetwork();
	}
	out << "</table></body></html>";
	
	out.close();

	AfxMessageBox("Done24!");
}

int LoadNetwork(char* fileName)
{ 
	ifstream inputFile;

	inputFile.open(fileName);
    
	if ((!inputFile.is_open()) || (inputFile.eof()))
	{
		return -1;
	}
    char name1[100];
    char name2[100];
	char acc1[100];
	char acc11[100];
    char acc2[100];
	char acc22[100];
	char rel[100];
	char type1[100];
	char type2[100];
	char loc1[100];
	char loc2[100];
	char typeOfInt[100];
    int i = 0;
	int interactionsCounter = 1;
    int num1, num2;
	int lineNumber = 0;
	int pmid;
	char pmidStr[100];
	int ret = 0;
	char line[3000];
	CString tempStr;
	CString tempStr1;
	int strIndex = 0;
	int wordCount = 0;
	int lineCount = 0;
	char temp[100];

    ret = LoadColorsAndShapes();

	if (ret == -1)
	{
		LoadColorsAndShapes();
		ret = 0;
	}

	//LoadVisioShapes();

	while ((!inputFile.eof()) && (i < 200000))
    {
		lineCount++;
		inputFile.getline(&line[0], 3000, '\n');
		tempStr = line;
		strIndex = 0;
		if (tempStr != "")
		{
			for (i= 0; i < 14; i++)
			{
				tempStr1 = tempStr.Tokenize(" \t", strIndex);
				if (((tempStr1 == "") && (i != 13)) ||
					((i == 13) && (tempStr1 != ""))) 
				{
					tempStr1.Format("%s line #%d to few columns\nThe program only accepts text files with 13 columns in each row!", tempStr.GetBuffer(), lineCount);
					AfxMessageBox(tempStr1.GetBuffer());
					inputFile.close();
					return -1;
				}	
			}
		}
	}
	
	inputFile.close();
	inputFile.clear(0);
	inputFile.open(fileName);
	if ((!inputFile.is_open()) || (inputFile.eof()))
	{
		return -1;
	}

	while ((!inputFile.eof()) && (i < 200000))
    { 
		name1[0] = 0;

		inputFile >> name1;
		if (!strcmp(name1, ""))
		{
			if (i == 0)
			{
				ret = -1;
			}
			break;
		}
		if (!strcmp(name1, "na"))
		{
			break;
		}
		inputFile >> acc1; //accSource;
		inputFile >> acc11;
		inputFile >> type1;
		inputFile >> loc1;
		inputFile >> name2;
		if (!strcmp(name2, "na"))
		{
			break;
		}
		inputFile >> acc2; //accTarget;
		inputFile >> acc22;
		inputFile >> type2;
		inputFile >> loc2;
		inputFile >> rel;
		inputFile >> typeOfInt;
		inputFile >> pmidStr;
		pmid = atoi(pmidStr);
		//inputFile.get(dummy);
		lineNumber++;

		//fix names that starts with numbers

		if ((name1[0] >= '0') && (name1[0] <= '9'))
		{
			strcpy(temp, name1);
			strcpy(name1, "P");
			strcat(name1, temp);
		}
		if ((name2[0] >= '0') && (name2[0] <= '9'))
		{
			strcpy(temp, name2);
			strcpy(name2, "P");
			strcat(name2, temp);
		}

		num2 = GetNumberBasedOnString(name2);
		MoleculesList = AddToMoleculesWithLink(name1, acc1, acc11, type1, loc1, num2);
		num1 = GetNumberBasedOnString(name1);
		MoleculesList = AddToMoleculesWithLink(name2, acc2, acc22, type2, loc2, num1);
		
		InteractionsList = AddToInteractions(name1, acc1, acc11, loc1, type1, name2, acc2, acc22,
						  loc2, type2, rel, typeOfInt, pmid);

	    i++;
    }

	inputFile.close();

	CountInAndOutLinks();

    return ret;
}


int LoadTwoColumnNetwork(char* fileName)
{ 
	ifstream inputFile;

	inputFile.open(fileName);
    
	if ((!inputFile.is_open()) || (inputFile.eof()))
	{
		return -1;
	}
    char name1[100];
    char name2[100];
	char acc1[100];
	char acc11[100];
    char acc2[100];
	char acc22[100];
	char rel[100];
	char type1[100];
	char type2[100];
	char loc1[100];
	char loc2[100];
	char typeOfInt[100];
    int i = 0;
	int interactionsCounter = 1;
    int num1, num2;
	int lineNumber = 0;
	int pmid;
	int ret = 0;
	char line[3000];
	CString tempStr;
	CString tempStr1;
	int strIndex = 0;
	int wordCount = 0;
	int lineCount = 0;

    ret = LoadColorsAndShapes();

	if (ret == -1)
	{
		LoadColorsAndShapes();
		ret = 0;
	}

	while ((!inputFile.eof()) && (i < 10000))
    {
		lineCount++;
		inputFile.getline(&line[0], 3000, '\n');
		tempStr = line;
		strIndex = 0;
		if (tempStr != "")
		{
			for (i= 0; i < 3; i++)
			{
				tempStr1 = tempStr.Tokenize(" \t", strIndex);
				if (((tempStr1 == "") && (i != 2)) ||
					((i == 2) && (tempStr1 != "")))
 				{
					tempStr1.Format("%s line #%d to few or too many columns\nThe load two column function only accepts text files with 2 columns in each row!", tempStr.GetBuffer(), lineCount);
					AfxMessageBox(tempStr1.GetBuffer());
					return -1;
				}	
			}
		}
	}
	
	inputFile.close();
	inputFile.clear(0);
	inputFile.open(fileName);
	if ((!inputFile.is_open()) || (inputFile.eof()))
	{
		return -1;
	}
	//LoadVisioShapes();

	while ((!inputFile.eof()) && (i < 10000))
    { 
		name1[0] = 0;

		inputFile >> name1;
		if (!strcmp(name1, ""))
		{
			if (i == 0)
			{
				ret = -1;
			}
			break;
		}
		if (!strcmp(name1, "na"))
		{
			break;
		}
		strcpy(acc1, "NA"); //accSource;
		strcpy(acc11, "NA");
		strcpy(type1, "NA");
		strcpy(loc1, "NA");
		inputFile >> name2;
		if (!strcmp(name2, "na"))
		{
			break;
		}
		strcpy(acc2, "NA"); //accSource;
		strcpy(acc22, "NA");
		strcpy(type2, "NA");
		strcpy(loc2, "NA");
		strcpy(rel, "0");
		strcpy(typeOfInt, "NA");
		pmid = 0;
		//inputFile.get(dummy);
		lineNumber++;

		num2 = GetNumberBasedOnString(name2);
		MoleculesList = AddToMoleculesWithLink(name1, acc1, acc11, type1, loc1, num2);
		num1 = GetNumberBasedOnString(name1);
		MoleculesList = AddToMoleculesWithLink(name2, acc2, acc22, type2, loc2, num1);
		
		InteractionsList = AddToInteractions(name1, acc1, acc11, loc1, type1, name2, acc2, acc22,
						  loc2, type2, rel, typeOfInt, pmid);

	    i++;
    }

	inputFile.close();

    return ret;
}

void FreeNetwork(void)
{
	FreeMoleculesList();
	FreeInteractionsList();
}

void DumpAllVisited(char* fileName)
{
	INTERACTION* tempNode;
	MOLECULE* tempNode1;
	MOLECULE* tempNode2;
	ofstream out;
	int numberOfInteractions = 0;
		
	out.open(fileName);

	tempNode = InteractionsList;

	while (tempNode)
	{
		tempNode1 = GetNodeBasedOnName(tempNode->source);
		tempNode2 = GetNodeBasedOnName(tempNode->target);

		if ((tempNode1->visited) && (tempNode2->visited))
		{
			out << tempNode->source << " " << tempNode->sourceAccHuman << " " << tempNode->sourceAccMouse << " " << tempNode->sourceType << " " << tempNode->sourceLocation << " " << tempNode->target << " " << tempNode->targetAccHuman << " " << tempNode->targetAccMouse << " ";
			out << tempNode->targetType << " " << tempNode->targetLocation << " " << tempNode->effect << " " << tempNode->typeOfInteraction << " " << tempNode->pmid << endl;
		}

		tempNode = tempNode->next;
	}
	out.close();
}

int CountAllVisited(void)
{
	MOLECULE* tempNode1;
	int count = 0;

	tempNode1 = MoleculesList;

	while (tempNode1)
	{
		if (tempNode1->visited)
		{
			count++;	
		}

		tempNode1 = tempNode1->next;
	}
		
	return count;
}

void AnalyzeSubNetworks(char* outputFile, int startIndex, int endIndex, char* fileNames)
{
	return;
}

void CTestSVGDlg::OnBnClickedButton21()
{
	MOLECULE* tempNode;
	char firstName[100];
	char secondName[100];
	char firstNameArray[50][100];
	char secondNameArray[50][100];
	int count = 0;
	int i;

	tempNode = MoleculesList;

	while (tempNode)
	{
		if (!strcmp(tempNode->moleculeType, "Ligand"))
		{
			sprintf(firstName, "%s_sub_nets_stats.htm", tempNode->name);
			sprintf(secondName, "%s_sub_net_depth", tempNode->name);
			strcpy(firstNameArray[count],  firstName);
			strcpy(secondNameArray[count], secondName);
			count++;
		}

		tempNode = tempNode->next;
	}
	for (i = 0; i < count; i++)
	{
		strcpy(firstName, firstNameArray[i]);
		strcpy(secondName, secondNameArray[i]);
		AnalyzeSubNetworks(firstName, 2, 15, secondName);
	}

	AfxMessageBox("Done25!");
}

void CTestSVGDlg::OnBnClickedButton22()
{
	MOLECULE* tempNode;
	ofstream out;
	ofstream out1;
	int negatives = 0;
	int positives = 0;
	int listSoFar[20];
	int i;
	char fileName[200];

	out.open("movie_pathways_count.htm");

	out << "<html><body><table>" << endl;
	out << "<tr><td>Name</td><td>Positives</td><td>Negatives</td><tr>" << endl;

	for (i = 6; i <= 6; i++)
	{
		tempNode = MoleculesList;

		while (tempNode)
		{
			if (!strcmp(tempNode->name, "GLUTAMATE"))
			{
				negatives = 0;
				positives = 0;
				listSoFar[0] = tempNode->number;
				strcpy(fileName, "MOVIE.sig");
				out1.open(fileName);
				ClearInteractionsFlag();
				IndexOfGlobalList = 0;
				CountNumberOfPathwaysToOutputAndDump(out1, "CREB", tempNode, i, 1, listSoFar, positives, negatives);
				AddInteractionsForFeedbackLoops(out1);
				out1.close();
				out << "<tr><td>" << tempNode->name << "</td><td>" << positives << "</td><td>" << negatives << "</td></tr>" << endl;
			}
			tempNode = tempNode->next;
		}
	}

	FreeNetwork();

	LoadNetwork("MOVIE.sig");

	//based on connectivty
	/*
	for (i = 2; i < 30; i++)
	{
		tempNode = MoleculesList;

		while (tempNode)
		{	
			tempNode->visited = 0;
			if (tempNode->linksCount < i)
			{
				tempNode->visited = 1;
			}
			tempNode = tempNode->next;
		}

		sprintf(fileName, "%d", i - 1);
		MakeSVGMapBasedOnVisited(fileName);
	}

	*/

	//based on connectivty
	int count;
	sprintf(fileName, "%d", 1);
	MakeSVGMapBasedOnVisited(fileName);
	ClearVisitedFlagForAllMolecules();
	tempNode = GetNodeBasedOnName("GLUTAMATE");
	tempNode->visited = 1;
	sprintf(fileName, "%d", 2);
	MakeSVGMapBasedOnVisited(fileName);
	for (i = 1; i <= 12; i++)
	{	
		count = 0;
		
		tempNode = GetNodeBasedOnName("GLUTAMATE");
		tempNode->visited = 1;
		count = ExpandSim(tempNode, i, count);

		sprintf(fileName, "%d", i + 2);
		MakeSVGMapBasedOnVisited(fileName);
	}


	AfxMessageBox("Done26!");
}

void CTestSVGDlg::OnBnClickedButton23()
{
	MOLECULE* tempNode;
	INTERACTION* tempInteraction;
	ofstream out;
	char source[100];
	out.open("list_of_dephospho_targets.txt");
	int flag;
	tempNode = MoleculesList;

	while (tempNode)
	{
		tempInteraction = InteractionsList;
		flag = 0;
		while (tempInteraction)
		{
			if ((!strcmp(tempInteraction->typeOfInteraction, "Phosphorylation")) && 
				(!strcmp(tempInteraction->target, tempNode->name)))
			{
				flag = 1;
				strcpy(source, tempInteraction->source);
				break;
			}
			tempInteraction = tempInteraction->next;
		}

		if (flag)
		{
			out << source << " " << tempNode->name << endl;
		}
		tempNode = tempNode->next;
	}
	out.close();

	out.open("list_of_phosphatases.txt");

	tempNode = MoleculesList;

	while (tempNode)
	{
		if (!strcmp(tempNode->moleculeType, "Phosphatase"))
		{
			out << tempNode->name << endl;
		}
		tempNode = tempNode->next;
	}

	out.close();
}

void CTestSVGDlg::OnBnClickedButton24()
{
	MOLECULE* tempNode;
	ofstream out;
	ofstream out1;
	int negatives = 0;
	int positives = 0;
	int listSoFar[20];
	int i;
	char fileName[200];

	out.open("GSK3_pathways_count.htm");

	out << "<html><body><table>" << endl;
	out << "<tr><td>Name</td><td>Positives</td><td>Negatives</td><tr>" << endl;

	for (i = 6; i <= 6; i++)
	{
		tempNode = MoleculesList;

		while (tempNode)
		{
			if (!strcmp(tempNode->name, "A3AR"))
			{
				negatives = 0;
				positives = 0;
				listSoFar[0] = tempNode->number;
				strcpy(fileName, "A3AR_TO_");
				strcat(fileName, tempNode->name);
				strcat(fileName, ".sig");
				out1.open(fileName);
				ClearInteractionsFlag();
				IndexOfGlobalList = 0;
				CountNumberOfPathwaysToOutputAndDump(out1, "GSK3", tempNode, i, 1, listSoFar, positives, negatives);
				AddInteractionsForFeedbackLoops(out1);
				out1.close();
				out << "<tr><td>" << tempNode->name << "</td><td>" << positives << "</td><td>" << negatives << "</td></tr>" << endl;
			}
			tempNode = tempNode->next;
		}
	}

	AfxMessageBox("Done27!");
}

void CTestSVGDlg::OnBnClickedButton25()
{
	ifstream connections;
    ofstream graph;
	MOLECULE* tempNode;
	MOLECULE* tempNode1;
	INTERACTION* tempInteraction;    
	graph.open("neuron.mol");
	char colorAndShape[100];
	char moleculeTypeIndex;
	double x, y, z;
	int source;
	int target;
	char sourceStr[10];
	char targetStr[10];
	char location[200];
	graph << "network.mol" << endl;
	graph << "-ISIS-            3D" << endl << endl;
	
	graph << NumberOfMolecules << NumberOfInteractions << endl;

	tempNode = MoleculesList;

	while (tempNode)
	{
		moleculeTypeIndex = GetMoleculeTypeIndex(tempNode->moleculeType);

		GetColorAndShape(moleculeTypeIndex, colorAndShape);

		if (!strcmp(tempNode->moleculeType, "Ligand"))
		{
			ComputeXYZ(1, x, y, z);
			sprintf(location, "%.4f", x);
			graph << "   ";
			if (strlen(location) == 6)
			{
				graph << " " << location;
			}
			else
			{
				graph << location;
			}
			sprintf(location, "%.4f", y);
			graph << "   ";
			if (strlen(location) == 6)
			{
				graph << " " << location;
			}
			else
			{
				graph << location;
			}
			sprintf(location, "%.4f", z);
			graph << "   ";
			if (strlen(location) == 6)
			{
				graph << " " << location;
			}
			else
			{
				graph << location;
			}
			graph << " N" << endl;
		}
		else if (!strcmp(tempNode->moleculeType, "Cytoskeleton"))
		{
			ComputeXYZ(2, x, y, z);
			sprintf(location, "%.4f", x);
			graph << "   ";
			if (strlen(location) == 6)
			{
				graph << " " << location;
			}
			else
			{
				graph << location;
			}
			sprintf(location, "%.4f", y);
			graph << "   ";
			if (strlen(location) == 6)
			{
				graph << " " << location;
			}
			else
			{
				graph << location;
			}
			sprintf(location, "%.4f", z);
			graph << "   ";
			if (strlen(location) == 6)
			{
				graph << " " << location;
			}
			else
			{
				graph << location;
			}
			graph << " C" << endl;
		}
		else if (!strcmp(tempNode->moleculeType, "TF"))
		{
			ComputeXYZ(3, x, y, z);
			sprintf(location, "%.4f", x);
			graph << "   ";
			if (strlen(location) == 6)
			{
				graph << " " << location;
			}
			else
			{
				graph << location;
			}
			sprintf(location, "%.4f", y);
			graph << "   ";
			if (strlen(location) == 6)
			{
				graph << " " << location;
			}
			else
			{
				graph << location;
			}
			sprintf(location, "%.4f", z);
			graph << "   ";
			if (strlen(location) == 6)
			{
				graph << " " << location;
			}
			else
			{
				graph << location;
			}
			graph << " Z" << endl;
		}
		else if (!strcmp(tempNode->location, "ER"))
		{
			ComputeXYZ(4, x, y, z);
			sprintf(location, "%.4f", x);
			graph << "   ";
			if (strlen(location) == 6)
			{
				graph << " " << location;
			}
			else
			{
				graph << location;
			}
			sprintf(location, "%.4f", y);
			graph << "   ";
			if (strlen(location) == 6)
			{
				graph << " " << location;
			}
			else
			{
				graph << location;
			}
			sprintf(location, "%.4f", z);
			graph << "   ";
			if (strlen(location) == 6)
			{
				graph << " " << location;
			}
			else
			{
				graph << location;
			}
			graph << " H" << endl;
		}
		else if (!strcmp(tempNode->location, "Membrane"))
		{
			ComputeXYZ(5, x, y, z);
			sprintf(location, "%.4f", x);
			graph << "   ";
			if (strlen(location) == 6)
			{
				graph << " " << location;
			}
			else
			{
				graph << location;
			}
			sprintf(location, "%.4f", y);
			graph << "   ";
			if (strlen(location) == 6)
			{
				graph << " " << location;
			}
			else
			{
				graph << location;
			}
			sprintf(location, "%.4f", z);
			graph << "   ";
			if (strlen(location) == 6)
			{
				graph << " " << location;
			}
			else
			{
				graph << location;
			}
			graph << " O" << endl;
		}
		else if (!strcmp(tempNode->location, "Vesicles"))
		{
			ComputeXYZ(6, x, y, z);
			sprintf(location, "%.4f", x);
			graph << "   ";
			if (strlen(location) == 6)
			{
				graph << " " << location;
			}
			else
			{
				graph << location;
			}
			sprintf(location, "%.4f", y);
			graph << "   ";
			if (strlen(location) == 6)
			{
				graph << " " << location;
			}
			else
			{
				graph << location;
			}
			sprintf(location, "%.4f", z);
			graph << "   ";
			if (strlen(location) == 6)
			{
				graph << " " << location;
			}
			else
			{
				graph << location;
			}
			graph << " R" << endl;
		}
		else if (!strcmp(tempNode->location, "Cytosol"))
		{
			ComputeXYZ(7, x, y, z);
			sprintf(location, "%.4f", x);
			graph << "   ";
			if (strlen(location) == 6)
			{
				graph << " " << location;
			}
			else
			{
				graph << location;
			}
			sprintf(location, "%.4f", y);
			graph << "   ";
			if (strlen(location) == 6)
			{
				graph << " " << location;
			}
			else
			{
				graph << location;
			}
			sprintf(location, "%.4f", z);
			graph << "   ";
			if (strlen(location) == 6)
			{
				graph << " " << location;
			}
			else
			{
				graph << location;
			}
			graph << " F" << endl;
		}
		else
		{
			ComputeXYZ(8, x, y, z);
			sprintf(location, "%.4f", x);
			graph << "   ";
			if (strlen(location) == 6)
			{
				graph << " " << location;
			}
			else
			{
				graph << location;
			}
			sprintf(location, "%.4f", y);
			graph << "   ";
			if (strlen(location) == 6)
			{
				graph << " " << location;
			}
			else
			{
				graph << location;
			}
			sprintf(location, "%.4f", z);
			graph << "   ";
			if (strlen(location) == 6)
			{
				graph << " " << location;
			}
			else
			{
				graph << location;
			}
			graph << " S" << endl;
		}
		tempNode = tempNode->next;
	}

	tempInteraction = InteractionsList;

	while (tempInteraction)
    { 
	    tempNode = GetNodeBasedOnName(tempInteraction->source);
		tempNode1 = GetNodeBasedOnName(tempInteraction->target);

		source = GetNumberBasedOnString(tempInteraction->source);
		target = GetNumberBasedOnString(tempInteraction->target);
		itoa(source, sourceStr, 10);
		itoa(target, targetStr, 10);

		if (strlen(sourceStr) == 1)
		{
			graph << source << "  " <<  target << endl;
		}
		else if (strlen(sourceStr) == 2)
		{
			graph << source << " " <<  target << endl;
		} 
		else
		{
			graph << source <<  target << endl;
		}

		tempInteraction = tempInteraction->next;
    }
	
	graph << "M END" << endl;
	graph.close();

	AfxMessageBox("Done28!");
    return;	
}

void ComputeXYZ(int area, double &x, double &y, double &z)
{
	int a,b,c, d;
	// ligand outer shell x^2 + y^2 + z^2 = 100
	a = GetRandomNumber(999) + 1;
	b = (int) (sqrt( (double) (GetRandomNumber(999999 - (a * a)))));
	d = 999999 - ((b * b) + (a * a));
	c = (int) (sqrt((double) d));

	if (area == 1)
	{
		x = a / 50.0;
		y = b / 50.0;
		z = c / 50.0;
	}
	else if ((area == 2) || (area == 4) || (area == 6) || (area == 7) || (area == 8))
	{
		x = a / (GetRandomNumber(20) + 70.0);
		y = b / (GetRandomNumber(20) + 70.0);
		z = c / (GetRandomNumber(20) + 70.0);
	}
	else if (area == 3)
	{
		x = a / (GetRandomNumber(20) + 110.0);
		y = b / (GetRandomNumber(20) + 110.0);
		z = c / (GetRandomNumber(20) + 110.0);
	}
	else if (area == 5)
	{
		x = a / 60.0;
		y = b / 60.0;
		z = c / 60.0;
	}
	/*
	a = GetRandomNumber(2);
	if (a == 0)
	{
		x = x * -1.0;
	}
	a = GetRandomNumber(2);
	if (a == 0)
	{
		y = y * -1.0;
	}
	a = GetRandomNumber(2);
	if (a == 0)
	{
		z = z * -1.0;
	}
    */	
}

void DumpNetwork(char* fileName)
{
	INTERACTION* tempNode;
	ofstream out;
	int i;

	out.open(fileName);
	
	tempNode = InteractionsList;

	while (tempNode)
	{
		for (i = 0; i < tempNode->referenceCount; i++)
		{
			out << tempNode->source << " " << tempNode->sourceAccHuman << " " << tempNode->sourceAccMouse << " " << tempNode->sourceType << " " << tempNode->sourceLocation << " " << tempNode->target << " ";
			out << tempNode->targetAccHuman << " " << tempNode->targetAccMouse << " " << tempNode->targetType << " " << tempNode->targetLocation << " " << tempNode->effect << " " << tempNode->typeOfInteraction << " " << tempNode->references[i] <<  endl;
		}
		
		tempNode = tempNode->next;
	}

	out.close();

	return;
}
void CTestSVGDlg::OnBnClickedButton26()
{
	int j;
	char fileName[100];

	ofstream out;
	out.open("motifs_for_shuffled_networks.htm");
	out << "<html><body><table>";
	out << "<tr><td>Network</td><td>31</td><td>32</td><td>41</td><td>42</td><td>51</td></tr>" << endl;
	FreeNetwork();

	for (j = 1; j <= 100; j++)
	{

		sprintf(fileName, "random_net%d.sig", j);
		LoadNetwork(fileName);
	
		//CountConvergedCycles();
		CountDirectedCycles(3, 0);
		
		out << "<tr><td>" << j << "</td><td>" << CountMotif31() << "</td><td>" << CountMotif32() << "</td><td>" << CountMotif41() << "</td><td>" << CountMotif42() << "</td><td>" << CountMotif51() << "</td></tr>" << endl;
		FreeMotifs();
		FreeNetwork();
	}
	out << "</table></body></html>";
	
	out.close();

	AfxMessageBox("Done29!");
}

MOTIF3* AddMotif3(char* name1, char* name2, char* name3)
{
	MOTIF3* tempNode;
	INTERACTION* tempInt;
	MOLECULE* tempMol;
	char type1[200];
	char type2[200];
	char type3[200];
	char effect1[200];
	char effect2[200];
	char effect3[200];
	char typeOfInteraction1[200];
	char typeOfInteraction2[200];
	char typeOfInteraction3[200];
	int direction1;
	int direction2;
	int direction3;

	if (These3NamesAlreadyBeenHere(name1, name2, name3))
	{
		return Motif3List;
	}

    /* if the list is empty */
    if (!Motif3List)
    {
         /* just store this information */
	    Motif3List = (MOTIF3*) malloc(sizeof(MOTIF3));
		tempMol = GetNodeBasedOnName(name1);
        strcpy(Motif3List->name1, tempMol->moleculeType);
		//strcpy(Motif3List->name1, tempMol->name);
		
		tempMol = GetNodeBasedOnName(name2);
        strcpy(Motif3List->name2, tempMol->moleculeType);
		//strcpy(Motif3List->name2, tempMol->name);

		tempMol = GetNodeBasedOnName(name3);
        strcpy(Motif3List->name3, tempMol->moleculeType);
		//strcpy(Motif3List->name3, tempMol->name);

		tempInt = InteractionsList;

		while (tempInt)
		{
			if (((!strcmp(tempInt->source, name1)) && (!strcmp(tempInt->target, name2)))
				|| ((!strcmp(tempInt->source, name2)) && (!strcmp(tempInt->target, name1))))
			{
				strcpy(Motif3List->effect1, tempInt->effect);
				strcpy(Motif3List->typeOfInteraction1, tempInt->typeOfInteraction);

				if (!strcmp(tempInt->effect, "0"))
				{
					Motif3List->direction1 = 0;
				}
				else if ((!strcmp(tempInt->source, name1)) && (!strcmp(tempInt->target, name2)))
				{
					Motif3List->direction1 = 1;
				}
				else
				{
					Motif3List->direction1 = -1;
				}
				break;
			}
			tempInt = tempInt->next;
		}

		tempInt = InteractionsList;

		while (tempInt)
		{
			if (((!strcmp(tempInt->source, name2)) && (!strcmp(tempInt->target, name3)))
				|| ((!strcmp(tempInt->source, name3)) && (!strcmp(tempInt->target, name2))))
			{
				strcpy(Motif3List->effect2, tempInt->effect);
				strcpy(Motif3List->typeOfInteraction2, tempInt->typeOfInteraction);

				if (!strcmp(tempInt->effect, "0"))
				{
					Motif3List->direction2 = 0;
				}
				else if ((!strcmp(tempInt->source, name2)) && (!strcmp(tempInt->target, name3)))
				{
					Motif3List->direction2 = 1;
				}
				else
				{
					Motif3List->direction2 = -1;
				}
				break;
			}
			tempInt = tempInt->next;
		}

		tempInt = InteractionsList;

		while (tempInt)
		{
			if (((!strcmp(tempInt->source, name1)) && (!strcmp(tempInt->target, name3)))
				|| ((!strcmp(tempInt->source, name3)) && (!strcmp(tempInt->target, name1))))
			{
				strcpy(Motif3List->effect3, tempInt->effect);
				strcpy(Motif3List->typeOfInteraction3, tempInt->typeOfInteraction);

				if (!strcmp(tempInt->effect, "0"))
				{
					Motif3List->direction3 = 0;
				}
				else if ((!strcmp(tempInt->source, name3)) && (!strcmp(tempInt->target, name1)))
				{
					Motif3List->direction3 = 1;
				}
				else
				{
					Motif3List->direction3 = -1;
				}
				break;
			}
			tempInt = tempInt->next;
		}

	    Motif3List->next = 0;
		Motif3List->count = 1;   
	    NumberOfMotif3++;
	    return Motif3List;	
    }

	tempMol = GetNodeBasedOnName(name1);
    strcpy(type1, tempMol->moleculeType);
	//strcpy(type1, tempMol->name);
		
	tempMol = GetNodeBasedOnName(name2);
    strcpy(type2, tempMol->moleculeType);
	//strcpy(type2, tempMol->name);

	tempMol = GetNodeBasedOnName(name3);
    strcpy(type3, tempMol->moleculeType);
	//strcpy(type3, tempMol->name);

	tempInt = InteractionsList;

	while (tempInt)
	{
		if (((!strcmp(tempInt->source, name1)) && (!strcmp(tempInt->target, name2)))
				|| ((!strcmp(tempInt->source, name2)) && (!strcmp(tempInt->target, name1))))
		{
			strcpy(effect1, tempInt->effect);
			strcpy(typeOfInteraction1, tempInt->typeOfInteraction);

			if (!strcmp(tempInt->effect, "0"))
			{
				direction1 = 0;
			}
			else if ((!strcmp(tempInt->source, name1)) && (!strcmp(tempInt->target, name2)))
			{
				direction1 = 1;
			}
			else
			{
				direction1 = -1;
			}
			break;
		}
		tempInt = tempInt->next;
	}

	tempInt = InteractionsList;

	while (tempInt)
	{
		if (((!strcmp(tempInt->source, name2)) && (!strcmp(tempInt->target, name3)))
				|| ((!strcmp(tempInt->source, name3)) && (!strcmp(tempInt->target, name2))))
		{
			strcpy(effect2, tempInt->effect);
			strcpy(typeOfInteraction2, tempInt->typeOfInteraction);

			if (!strcmp(tempInt->effect, "0"))
			{
				direction2 = 0;
			}
			else if ((!strcmp(tempInt->source, name2)) && (!strcmp(tempInt->target, name3)))
			{
				direction2 = 1;
			}
			else
			{
				direction2 = -1;
			}
			break;
		}
		tempInt = tempInt->next;
	}

	tempInt = InteractionsList;

	while (tempInt)
	{
		if (((!strcmp(tempInt->source, name1)) && (!strcmp(tempInt->target, name3)))
			|| ((!strcmp(tempInt->source, name3)) && (!strcmp(tempInt->target, name1))))
		{
			strcpy(effect3, tempInt->effect);
			strcpy(typeOfInteraction3, tempInt->typeOfInteraction);
			if (!strcmp(tempInt->effect, "0"))
			{
				direction3 = 0;
			}
			else if ((!strcmp(tempInt->source, name3)) && (!strcmp(tempInt->target, name1)))
			{
				direction3 = 1;
			}
			else
			{
				direction3 = -1;
			}
			break;
		}
		tempInt = tempInt->next;
	}

	/* look for a match or loop all the way to the end */
    tempNode = Motif3List;

    /* loop until a match was found or the end */
    while ((tempNode->next != 0) && 
		(
		 (strcmp(tempNode->name1, type1)) || 
		 (strcmp(tempNode->name2, type2)) || 
		 (strcmp(tempNode->name3, type3)) ||
		 (strcmp(tempNode->effect1, effect1)) || 
		 (strcmp(tempNode->effect2, effect2)) || 
		 (strcmp(tempNode->effect3, effect3)) ||
		 (direction1 != tempNode->direction1) || 
		 (direction2 != tempNode->direction2) || 
		 (direction3 != tempNode->direction3)
		 ) &&

		(
		 (strcmp(tempNode->name1, type2)) || 
		 (strcmp(tempNode->name2, type3)) || 
		 (strcmp(tempNode->name3, type1)) ||
		 (strcmp(tempNode->effect1, effect2)) || 
		 (strcmp(tempNode->effect2, effect3)) || 
		 (strcmp(tempNode->effect3, effect1)) ||
		 (direction2 != tempNode->direction1) || 
		 (direction3 != tempNode->direction2) || 
		 (direction1 != tempNode->direction3)
		 ) &&

		 (
		 (strcmp(tempNode->name1, type3)) || 
		 (strcmp(tempNode->name2, type1)) || 
		 (strcmp(tempNode->name3, type2)) ||
		 (strcmp(tempNode->effect1, effect3)) || 
		 (strcmp(tempNode->effect2, effect1)) || 
		 (strcmp(tempNode->effect3, effect2)) ||
		 (direction3 != tempNode->direction1) || 
		 (direction1 != tempNode->direction2) || 
		 (direction2 != tempNode->direction3)
		 ) &&

		 (
		 (strcmp(tempNode->name1, type1)) || 
		 (strcmp(tempNode->name2, type3)) || 
		 (strcmp(tempNode->name3, type2)) ||
		 (strcmp(tempNode->effect1, effect1)) || 
		 (strcmp(tempNode->effect2, effect3)) || 
		 (strcmp(tempNode->effect3, effect2)) ||
		 (direction1 != tempNode->direction1) || 
		 (direction3 != tempNode->direction2) || 
		 (direction2 != tempNode->direction3)
		 ) &&

		 (
		 (strcmp(tempNode->name1, type2)) || 
		 (strcmp(tempNode->name2, type1)) || 
		 (strcmp(tempNode->name3, type3)) ||
		 (strcmp(tempNode->effect1, effect2)) || 
		 (strcmp(tempNode->effect2, effect1)) || 
		 (strcmp(tempNode->effect3, effect3)) ||
		 (direction2 != tempNode->direction1) || 
		 (direction1 != tempNode->direction2) || 
		 (direction3 != tempNode->direction3)
		 ) &&

		 (
		 (strcmp(tempNode->name1, type3)) || 
		 (strcmp(tempNode->name2, type2)) || 
		 (strcmp(tempNode->name3, type1)) ||
		 (strcmp(tempNode->effect1, effect3)) || 
		 (strcmp(tempNode->effect2, effect2)) || 
		 (strcmp(tempNode->effect3, effect1)) ||
		 (direction3 != tempNode->direction1) || 
		 (direction2 != tempNode->direction2) || 
		 (direction1 != tempNode->direction3)
		 ) 
		)
    {
	    tempNode = tempNode->next;
    }

    /* if a match was found add one to the count */
    if ( 
		 ((!strcmp(tempNode->name1, type1)) && 
		  (!strcmp(tempNode->name2, type2)) && 
		  (!strcmp(tempNode->name3, type3)) &&
		  (!strcmp(tempNode->effect1, effect1)) && 
		  (!strcmp(tempNode->effect2, effect2)) && 
		  (!strcmp(tempNode->effect3, effect3)) &&
		  (direction1 == tempNode->direction1) && 
		  (direction2 == tempNode->direction2) && 
		  (direction3 == tempNode->direction3)
		  )
		  ||
		  (
		  (!strcmp(tempNode->name1, type2)) && 
		  (!strcmp(tempNode->name2, type3)) && 
		  (!strcmp(tempNode->name3, type1)) &&
		  (!strcmp(tempNode->effect1, effect2)) && 
		  (!strcmp(tempNode->effect2, effect3)) && 
		  (!strcmp(tempNode->effect3, effect1)) &&
		  (direction2 == tempNode->direction1) && 
		  (direction3 == tempNode->direction2) && 
		  (direction1 == tempNode->direction3)
		 )
		 ||
		 (
		  (!strcmp(tempNode->name1, type3)) && 
		  (!strcmp(tempNode->name2, type1)) && 
		  (!strcmp(tempNode->name3, type2)) &&
		  (!strcmp(tempNode->effect1, effect3)) && 
		  (!strcmp(tempNode->effect2, effect1)) && 
		  (!strcmp(tempNode->effect3, effect2)) &&
		  (direction3 == tempNode->direction1) && 
		  (direction1 == tempNode->direction2) && 
		  (direction2 == tempNode->direction3)
		 )
		 ||
		 (
		  (!strcmp(tempNode->name1, type1)) && 
		  (!strcmp(tempNode->name2, type3)) && 
		  (!strcmp(tempNode->name3, type2)) &&
		  (!strcmp(tempNode->effect1, effect1)) && 
		  (!strcmp(tempNode->effect2, effect3)) && 
		  (!strcmp(tempNode->effect3, effect2)) &&
		  (direction1 == tempNode->direction1) && 
		  (direction3 == tempNode->direction2) && 
		  (direction2 == tempNode->direction3)
		 )
		 ||
		 (
		  (!strcmp(tempNode->name1, type2)) && 
		  (!strcmp(tempNode->name2, type1)) && 
		  (!strcmp(tempNode->name3, type3)) &&
		  (!strcmp(tempNode->effect1, effect2)) && 
		  (!strcmp(tempNode->effect2, effect1)) && 
		  (!strcmp(tempNode->effect3, effect3)) &&
		  (direction3 == tempNode->direction1) && 
		  (direction1 == tempNode->direction2) && 
		  (direction2 == tempNode->direction3)
		 )
		 ||
		 (
		  (!strcmp(tempNode->name1, type3)) && 
		  (!strcmp(tempNode->name2, type2)) && 
		  (!strcmp(tempNode->name3, type1)) &&
		  (!strcmp(tempNode->effect1, effect3)) && 
		  (!strcmp(tempNode->effect2, effect2)) && 
		  (!strcmp(tempNode->effect3, effect1)) &&
		  (direction3 == tempNode->direction1) && 
		  (direction2 == tempNode->direction2) && 
		  (direction1 == tempNode->direction3)
		 )
		 )
    {
		/* check if the link is already there */
		tempNode->count++;

		return Motif3List;
    }
    
	 /* just store this information */
	tempNode->next = (MOTIF3*) malloc(sizeof(MOTIF3));
	tempNode = tempNode->next;
    strcpy(tempNode->name1, type1);
    strcpy(tempNode->name2, type2);
    strcpy(tempNode->name3, type3);
	//strcpy(tempNode->name1, name1);
    //strcpy(tempNode->name2, name2);
    //strcpy(tempNode->name3, name3);
	strcpy(tempNode->effect1, effect1);
    strcpy(tempNode->effect2, effect2);
    strcpy(tempNode->effect3, effect3);
	strcpy(tempNode->typeOfInteraction1, typeOfInteraction1);
    strcpy(tempNode->typeOfInteraction2, typeOfInteraction2);
    strcpy(tempNode->typeOfInteraction3, typeOfInteraction3);
	tempNode->direction1 = direction1;
	tempNode->direction2 = direction2;
	tempNode->direction3 = direction3;
	tempNode->next = 0;
    tempNode->count = 1;
	NumberOfMotif3++;
	return Motif3List;	
}

MOTIF4* AddMotif4(char* name1, char* name2, char* name3, char* name4)
{
	MOTIF4* tempNode;
	INTERACTION* tempInt;
	MOLECULE* tempMol;
	char type1[200];
	char type2[200];
	char type3[200];
	char type4[200];
	char effect1[200];
	char effect2[200];
	char effect3[200];
	char effect4[200];
	int direction1;
	int direction2;
	int direction3;
	int direction4;
	char typeOfInteraction1[200];
	char typeOfInteraction2[200];
	char typeOfInteraction3[200];
	char typeOfInteraction4[200];

	if ((These4NamesAlreadyBeenHere(name1, name2, name3, name4)) ||
		(AreThereInBetweenThese4Connections(name1, name2, name3, name4)))
	{
		return Motif4List;
	}

    /* if the list is empty */
    if (!Motif4List)
    {
         /* just store this information */
	    Motif4List = (MOTIF4*) malloc(sizeof(MOTIF4));
		tempMol = GetNodeBasedOnName(name1);
        strcpy(Motif4List->name1, tempMol->moleculeType);
		
		tempMol = GetNodeBasedOnName(name2);
        strcpy(Motif4List->name2, tempMol->moleculeType);

		tempMol = GetNodeBasedOnName(name3);
        strcpy(Motif4List->name3, tempMol->moleculeType);

		tempMol = GetNodeBasedOnName(name4);
        strcpy(Motif4List->name4, tempMol->moleculeType);

		tempInt = InteractionsList;

		while (tempInt)
		{
			if (((!strcmp(tempInt->source, name1)) && (!strcmp(tempInt->target, name2)))
				|| ((!strcmp(tempInt->source, name2)) && (!strcmp(tempInt->target, name1))))
			{
				strcpy(Motif4List->effect1, tempInt->effect);
				strcpy(Motif4List->typeOfInteraction1, tempInt->typeOfInteraction);
				if (!strcmp(tempInt->effect, "0"))
				{
					Motif4List->direction1 = 0;
				}
				else if ((!strcmp(tempInt->source, name1)) && (!strcmp(tempInt->target, name2)))
				{
					Motif4List->direction1 = 1;
				}
				else
				{
					Motif4List->direction1 = -1;
				}
				break;
			}
			tempInt = tempInt->next;
		}

		tempInt = InteractionsList;

		while (tempInt)
		{
			if (((!strcmp(tempInt->source, name2)) && (!strcmp(tempInt->target, name3)))
				|| ((!strcmp(tempInt->source, name3)) && (!strcmp(tempInt->target, name2))))
			{
				strcpy(Motif4List->effect2, tempInt->effect);
				strcpy(Motif4List->typeOfInteraction2, tempInt->typeOfInteraction);
				if (!strcmp(tempInt->effect, "0"))
				{
					Motif4List->direction2 = 0;
				}
				else if ((!strcmp(tempInt->source, name2)) && (!strcmp(tempInt->target, name3)))
				{
					Motif4List->direction2 = 1;
				}
				else
				{
					Motif4List->direction2 = -1;
				}
				break;
			}
			tempInt = tempInt->next;
		}

		tempInt = InteractionsList;

		while (tempInt)
		{
			if (((!strcmp(tempInt->source, name4)) && (!strcmp(tempInt->target, name3)))
				|| ((!strcmp(tempInt->source, name3)) && (!strcmp(tempInt->target, name4))))
			{
				strcpy(Motif4List->effect3, tempInt->effect);
				strcpy(Motif4List->typeOfInteraction3, tempInt->typeOfInteraction);
				if (!strcmp(tempInt->effect, "0"))
				{
					Motif4List->direction3 = 0;
				}
				else if ((!strcmp(tempInt->source, name3)) && (!strcmp(tempInt->target, name4)))
				{
					Motif4List->direction3 = 1;
				}
				else
				{
					Motif4List->direction3 = -1;
				}
				break;
			}
			tempInt = tempInt->next;
		}

		tempInt = InteractionsList;

		while (tempInt)
		{
			if (((!strcmp(tempInt->source, name1)) && (!strcmp(tempInt->target, name4)))
				|| ((!strcmp(tempInt->source, name4)) && (!strcmp(tempInt->target, name1))))
			{
				strcpy(Motif4List->effect4, tempInt->effect);
				strcpy(Motif4List->typeOfInteraction4, tempInt->typeOfInteraction);
				if (!strcmp(tempInt->effect, "0"))
				{
					Motif4List->direction4 = 0;
				}
				else if ((!strcmp(tempInt->source, name4)) && (!strcmp(tempInt->target, name1)))
				{
					Motif4List->direction4 = 1;
				}
				else
				{
					Motif4List->direction4 = -1;
				}
				break;
			}
			tempInt = tempInt->next;
		}

	    Motif4List->next = 0;
		Motif4List->count = 1;   
	    NumberOfMotif4++;
	    return Motif4List;	
    }
    
    
    /* look for a match or loop all the way to the end */
    tempNode = Motif4List;

	tempMol = GetNodeBasedOnName(name1);
    strcpy(type1, tempMol->moleculeType);
		
	tempMol = GetNodeBasedOnName(name2);
    strcpy(type2, tempMol->moleculeType);

	tempMol = GetNodeBasedOnName(name3);
    strcpy(type3, tempMol->moleculeType);

	tempMol = GetNodeBasedOnName(name4);
    strcpy(type4, tempMol->moleculeType);

	tempInt = InteractionsList;

	while (tempInt)
	{
		if (((!strcmp(tempInt->source, name1)) && (!strcmp(tempInt->target, name2)))
				|| ((!strcmp(tempInt->source, name2)) && (!strcmp(tempInt->target, name1))))
		{
			strcpy(effect1, tempInt->effect);
			strcpy(typeOfInteraction1, tempInt->typeOfInteraction);
			if (!strcmp(tempInt->effect, "0"))
			{
				direction1 = 0;
			}
			else if ((!strcmp(tempInt->source, name1)) && (!strcmp(tempInt->target, name2)))
			{
				direction1 = 1;
			}
			else
			{
				direction1 = -1;
			}
			break;
		}
		tempInt = tempInt->next;
	}

	tempInt = InteractionsList;

	while (tempInt)
	{
		if (((!strcmp(tempInt->source, name2)) && (!strcmp(tempInt->target, name3)))
				|| ((!strcmp(tempInt->source, name3)) && (!strcmp(tempInt->target, name2))))
		{
			strcpy(effect2, tempInt->effect);
			strcpy(typeOfInteraction2, tempInt->typeOfInteraction);
			if (!strcmp(tempInt->effect, "0"))
			{
				direction2 = 0;
			}
			else if ((!strcmp(tempInt->source, name2)) && (!strcmp(tempInt->target, name3)))
			{
				direction2 = 1;
			}
			else
			{
				direction2 = -1;
			}
			break;
		}
		tempInt = tempInt->next;
	}

	tempInt = InteractionsList;

	while (tempInt)
	{
		if (((!strcmp(tempInt->source, name3)) && (!strcmp(tempInt->target, name4)))
			|| ((!strcmp(tempInt->source, name4)) && (!strcmp(tempInt->target, name3))))
		{
			strcpy(effect3, tempInt->effect);
			strcpy(typeOfInteraction3, tempInt->typeOfInteraction);
			if (!strcmp(tempInt->effect, "0"))
			{
				direction3 = 0;
			}
			else if ((!strcmp(tempInt->source, name3)) && (!strcmp(tempInt->target, name4)))
			{
				direction3 = 1;
			}
			else
			{
				direction3 = -1;
			}
			break;
		}
		tempInt = tempInt->next;
	}

	tempInt = InteractionsList;

	while (tempInt)
	{
		if (((!strcmp(tempInt->source, name1)) && (!strcmp(tempInt->target, name4)))
			|| ((!strcmp(tempInt->source, name4)) && (!strcmp(tempInt->target, name1))))
		{
			strcpy(effect4, tempInt->effect);
			strcpy(typeOfInteraction4, tempInt->typeOfInteraction);
			if (!strcmp(tempInt->effect, "0"))
			{
				direction4 = 0;
			}
			else if ((!strcmp(tempInt->source, name4)) && (!strcmp(tempInt->target, name1)))
			{
				direction4 = 1;
			}
			else
			{
				direction4 = -1;
			}
			break;
		}
		tempInt = tempInt->next;
	}

    /* loop until a match was found or the end */
    while ((tempNode->next != 0) && 
		((strcmp(tempNode->name1, type1)) || 
		 (strcmp(tempNode->name2, type2)) || 
		 (strcmp(tempNode->name3, type3)) || 
		 (strcmp(tempNode->name4, type4)) ||
		 (strcmp(tempNode->effect1, effect1)) || 
		 (strcmp(tempNode->effect2, effect2)) || 
		 (strcmp(tempNode->effect3, effect3)) || 
		 (strcmp(tempNode->effect4, effect4)) ||
		 (tempNode->direction1 != direction1) || 
		 (tempNode->direction2 != direction2) || 
		 (tempNode->direction3 != direction3) || 
		 (tempNode->direction4 != direction4))
		 &&
		((strcmp(tempNode->name1, type2)) || 
		 (strcmp(tempNode->name2, type3)) || 
		 (strcmp(tempNode->name3, type4)) || 
		 (strcmp(tempNode->name4, type1)) ||
		 (strcmp(tempNode->effect1, effect2)) || 
		 (strcmp(tempNode->effect2, effect3)) || 
		 (strcmp(tempNode->effect3, effect4)) || 
		 (strcmp(tempNode->effect4, effect1)) ||
		 (tempNode->direction1 != direction2) || 
		 (tempNode->direction2 != direction3) || 
		 (tempNode->direction3 != direction4) || 
		 (tempNode->direction4 != direction1))
		 &&
		 ((strcmp(tempNode->name1, type3)) || 
		  (strcmp(tempNode->name2, type4)) || 
		  (strcmp(tempNode->name3, type1)) || 
		  (strcmp(tempNode->name4, type2)) ||
		  (strcmp(tempNode->effect1, effect3)) || 
		  (strcmp(tempNode->effect2, effect4)) || 
		  (strcmp(tempNode->effect3, effect1)) || 
		  (strcmp(tempNode->effect4, effect2)) ||
		  (tempNode->direction1 != direction3) || 
		  (tempNode->direction2 != direction4) || 
		  (tempNode->direction3 != direction1) || 
		  (tempNode->direction4 != direction2))
		 &&
		 (
		 (strcmp(tempNode->name1, type4)) || 
		 (strcmp(tempNode->name2, type1)) || 
		 (strcmp(tempNode->name3, type2)) || 
		 (strcmp(tempNode->name4, type3)) ||
		 (strcmp(tempNode->effect1, effect4)) || 
		 (strcmp(tempNode->effect2, effect1)) || 
		 (strcmp(tempNode->effect3, effect2)) || 
		 (strcmp(tempNode->effect4, effect3)) ||
		 (tempNode->direction1 != direction4) || 
		 (tempNode->direction2 != direction1) || 
		 (tempNode->direction3 != direction2) || 
		 (tempNode->direction4 != direction3)
		 )
		 &&
		 (
		 (strcmp(tempNode->name1, type1)) || 
		 (strcmp(tempNode->name2, type4)) || 
		 (strcmp(tempNode->name3, type3)) || 
		 (strcmp(tempNode->name4, type2)) ||
		 (strcmp(tempNode->effect1, effect1)) || 
		 (strcmp(tempNode->effect2, effect4)) || 
		 (strcmp(tempNode->effect3, effect3)) || 
		 (strcmp(tempNode->effect4, effect2)) ||
		 (tempNode->direction1 != direction1) || 
		 (tempNode->direction2 != direction4) || 
		 (tempNode->direction3 != direction3) || 
		 (tempNode->direction4 != direction2)
		 )
		 &&
		 (
		 (strcmp(tempNode->name1, type2)) || 
		 (strcmp(tempNode->name2, type1)) || 
		 (strcmp(tempNode->name3, type4)) || 
		 (strcmp(tempNode->name4, type3)) ||
		 (strcmp(tempNode->effect1, effect2)) || 
		 (strcmp(tempNode->effect2, effect1)) || 
		 (strcmp(tempNode->effect3, effect4)) || 
		 (strcmp(tempNode->effect4, effect3)) ||
		 (tempNode->direction1 != direction2) || 
		 (tempNode->direction2 != direction1) || 
		 (tempNode->direction3 != direction4) || 
		 (tempNode->direction4 != direction3)
		 )
		 &&
		 (
		 (strcmp(tempNode->name1, type3)) || 
		 (strcmp(tempNode->name2, type2)) || 
		 (strcmp(tempNode->name3, type1)) || 
		 (strcmp(tempNode->name4, type4)) ||
		 (strcmp(tempNode->effect1, effect3)) || 
		 (strcmp(tempNode->effect2, effect2)) || 
		 (strcmp(tempNode->effect3, effect1)) || 
		 (strcmp(tempNode->effect4, effect4)) ||
		 (tempNode->direction1 != direction3) || 
		 (tempNode->direction2 != direction2) || 
		 (tempNode->direction3 != direction1) || 
		 (tempNode->direction4 != direction4)
		 )
		 &&
		 (
		 (strcmp(tempNode->name1, type4)) || 
		 (strcmp(tempNode->name2, type3)) || 
		 (strcmp(tempNode->name3, type2)) || 
		 (strcmp(tempNode->name4, type1)) ||
		 (strcmp(tempNode->effect1, effect4)) || 
		 (strcmp(tempNode->effect2, effect3)) || 
		 (strcmp(tempNode->effect3, effect2)) || 
		 (strcmp(tempNode->effect4, effect1)) ||
		 (tempNode->direction1 != direction4) || 
		 (tempNode->direction2 != direction3) || 
		 (tempNode->direction3 != direction2) || 
		 (tempNode->direction4 != direction1)
		 )
		 )
    {
	    tempNode = tempNode->next;
    }

    /* if a match was found add one to the count */
    if (
		 ((!strcmp(tempNode->name1, type1)) && 
		  (!strcmp(tempNode->name2, type2)) && 
		  (!strcmp(tempNode->name3, type3)) && 
		  (!strcmp(tempNode->name4, type4)) &&
		  (!strcmp(tempNode->effect1, effect1)) && 
		  (!strcmp(tempNode->effect2, effect2)) && 
		  (!strcmp(tempNode->effect3, effect3)) && 
		  (!strcmp(tempNode->effect4, effect4)) &&
		  (tempNode->direction1 == direction1) && 
		  (tempNode->direction2 == direction2) && 
		  (tempNode->direction3 == direction3) && 
		  (tempNode->direction4 == direction4))
		 ||
		 ((!strcmp(tempNode->name1, type2)) && 
		  (!strcmp(tempNode->name2, type3)) && 
		  (!strcmp(tempNode->name3, type4)) && 
		  (!strcmp(tempNode->name4, type1)) &&
		  (!strcmp(tempNode->effect1, effect2)) && 
		  (!strcmp(tempNode->effect2, effect3)) && 
		  (!strcmp(tempNode->effect3, effect4)) && 
		  (!strcmp(tempNode->effect4, effect1)) &&
		  (tempNode->direction1 == direction2) && 
		  (tempNode->direction2 == direction3) && 
		  (tempNode->direction3 == direction4) && 
		  (tempNode->direction4 == direction1))
		 ||
		 ((!strcmp(tempNode->name1, type3)) && 
		  (!strcmp(tempNode->name2, type4)) && 
		  (!strcmp(tempNode->name3, type1)) && 
		  (!strcmp(tempNode->name4, type2)) &&
		  (!strcmp(tempNode->effect1, effect3)) && 
		  (!strcmp(tempNode->effect2, effect4)) && 
		  (!strcmp(tempNode->effect3, effect1)) && 
		  (!strcmp(tempNode->effect4, effect2)) &&
		  (tempNode->direction1 == direction3) && 
		  (tempNode->direction2 == direction4) && 
		  (tempNode->direction3 == direction1) && 
		  (tempNode->direction4 == direction2))
		 ||
		 (
		 (!strcmp(tempNode->name1, type4)) && 
		 (!strcmp(tempNode->name2, type1)) && 
		 (!strcmp(tempNode->name3, type2)) && 
		 (!strcmp(tempNode->name4, type3)) &&
		 (!strcmp(tempNode->effect1, effect4)) && 
		 (!strcmp(tempNode->effect2, effect1)) && 
		 (!strcmp(tempNode->effect3, effect2)) && 
		 (!strcmp(tempNode->effect4, effect3)) &&
		 (tempNode->direction1 == direction4) && 
		 (tempNode->direction2 == direction1) && 
		 (tempNode->direction3 == direction2) && 
		 (tempNode->direction4 == direction3)
		 )
		 ||
		 (
		 (!strcmp(tempNode->name1, type1)) && 
		 (!strcmp(tempNode->name2, type4)) && 
		 (!strcmp(tempNode->name3, type3)) && 
		 (!strcmp(tempNode->name4, type2)) &&
		 (!strcmp(tempNode->effect1, effect1)) && 
		 (!strcmp(tempNode->effect2, effect4)) && 
		 (!strcmp(tempNode->effect3, effect3)) && 
		 (!strcmp(tempNode->effect4, effect2)) &&
		 (tempNode->direction1 == direction1) && 
		 (tempNode->direction2 == direction4) && 
		 (tempNode->direction3 == direction3) && 
		 (tempNode->direction4 == direction2)
		 )
		 ||
		 (
		 (!strcmp(tempNode->name1, type2)) && 
		 (!strcmp(tempNode->name2, type1)) && 
		 (!strcmp(tempNode->name3, type4)) && 
		 (!strcmp(tempNode->name4, type3)) &&
		 (!strcmp(tempNode->effect1, effect2)) && 
		 (!strcmp(tempNode->effect2, effect1)) && 
		 (!strcmp(tempNode->effect3, effect4)) && 
		 (!strcmp(tempNode->effect4, effect3)) &&
		 (tempNode->direction1 == direction2) && 
		 (tempNode->direction2 == direction1) && 
		 (tempNode->direction3 == direction4) && 
		 (tempNode->direction4 == direction3)
		 )
		 ||
		 (
		 (!strcmp(tempNode->name1, type3)) && 
		 (!strcmp(tempNode->name2, type2)) && 
		 (!strcmp(tempNode->name3, type1)) && 
		 (!strcmp(tempNode->name4, type4)) &&
		 (!strcmp(tempNode->effect1, effect3)) && 
		 (!strcmp(tempNode->effect2, effect2)) && 
		 (!strcmp(tempNode->effect3, effect1)) && 
		 (!strcmp(tempNode->effect4, effect4)) &&
		 (tempNode->direction1 == direction3) && 
		 (tempNode->direction2 == direction2) && 
		 (tempNode->direction3 == direction1) && 
		 (tempNode->direction4 == direction4)
		 )
		 ||
		 (
		 (!strcmp(tempNode->name1, type4)) && 
		 (!strcmp(tempNode->name2, type3)) && 
		 (!strcmp(tempNode->name3, type2)) && 
		 (!strcmp(tempNode->name4, type1)) &&
		 (!strcmp(tempNode->effect1, effect4)) && 
		 (!strcmp(tempNode->effect2, effect3)) && 
		 (!strcmp(tempNode->effect3, effect2)) && 
		 (!strcmp(tempNode->effect4, effect1)) &&
		 (tempNode->direction1 == direction4) && 
		 (tempNode->direction2 == direction3) && 
		 (tempNode->direction3 == direction2) && 
		 (tempNode->direction4 == direction1)
		 )
	   )
    {
		/* check if the link is already there */
		tempNode->count++;

		return Motif4List;
    }
    
	 /* just store this information */
	tempNode->next = (MOTIF4*) malloc(sizeof(MOTIF4));
	tempNode = tempNode->next;
    strcpy(tempNode->name1, type1);
    strcpy(tempNode->name2, type2);
    strcpy(tempNode->name3, type3);
	strcpy(tempNode->name4, type4);
	strcpy(tempNode->effect1, effect1);
    strcpy(tempNode->effect2, effect2);
    strcpy(tempNode->effect3, effect3);
	strcpy(tempNode->effect4, effect4);
	strcpy(tempNode->typeOfInteraction1, typeOfInteraction1);
    strcpy(tempNode->typeOfInteraction2, typeOfInteraction2);
    strcpy(tempNode->typeOfInteraction3, typeOfInteraction3);
	strcpy(tempNode->typeOfInteraction4, typeOfInteraction4);
	tempNode->direction1 = direction1;
	tempNode->direction2 = direction2;
	tempNode->direction3 = direction3;
	tempNode->direction4 = direction4;

	tempNode->next = 0;
    tempNode->count = 1;
	NumberOfMotif4++;
	return Motif4List;	
}

void DumpMotif3List(void)
{
	MOTIF3* tempNode;
	ofstream out;

	out.open("motif3.txt");
	
	tempNode = Motif3List;

	while (tempNode)
	{
		out << tempNode->name1 << " " << tempNode->typeOfInteraction1 << " " << tempNode->effect1 << " " << tempNode->direction1 << " ";
		out << tempNode->name2 << " " << tempNode->typeOfInteraction2 << " " << tempNode->effect2 << " " << tempNode->direction2 << " ";
		out << tempNode->name3 << " " << tempNode->typeOfInteraction3 << " " << tempNode->effect3 << " " << tempNode->direction3 << " " << tempNode->count <<  endl;
		
		tempNode = tempNode->next;
	}

	out.close();

	return;
}

void DumpMotif4List(void)
{
	MOTIF4* tempNode;
	ofstream out;

	out.open("motif4.txt");
	
	tempNode = Motif4List;

	while (tempNode)
	{
		out << tempNode->name1 << " " << tempNode->typeOfInteraction1 << " " << tempNode->effect1 << " " << tempNode->direction1 << " ";
		out << tempNode->name2 << " " << tempNode->typeOfInteraction2 << " " << tempNode->effect2 << " " << tempNode->direction2 << " ";
		out << tempNode->name3 << " " << tempNode->typeOfInteraction3 << " " << tempNode->effect3 << " " << tempNode->direction3 << " ";
		out << tempNode->name4 << " " << tempNode->typeOfInteraction4 << " " << tempNode->effect4 << " " << tempNode->direction4 << " " << tempNode->count <<  endl;
				
		tempNode = tempNode->next;
	}

	out.close();

	return;
}

void DumpMotif5List(void)
{
	MOTIF5* tempNode;
	ofstream out;

	out.open("motif5.txt");
	
	tempNode = Motif5List;

	while (tempNode)
	{
		out << tempNode->name1 << " " << tempNode->typeOfInteraction1 << " " << tempNode->effect1 << " " << tempNode->direction1 << " ";
		out << tempNode->name2 << " " << tempNode->typeOfInteraction2 << " " << tempNode->effect2 << " " << tempNode->direction2 << " ";
		out << tempNode->name3 << " " << tempNode->typeOfInteraction3 << " " << tempNode->effect3 << " " << tempNode->direction3 << " ";
		out << tempNode->name4 << " " << tempNode->typeOfInteraction4 << " " << tempNode->effect4 << " " << tempNode->direction4 << " ";
		out << tempNode->name5 << " " << tempNode->typeOfInteraction5 << " " << tempNode->effect5 << " " << tempNode->direction5 << " " << tempNode->count <<  endl;
		
		tempNode = tempNode->next;
	}

	out.close();

	return;
}
void CTestSVGDlg::OnBnClickedButton27()
{	
	ofstream out;
	int motifs31;
	int motifs32;
	int motifs33;
	int motifs34;
	int motifs35;
	int motifs36;
	int motifs41;
	int motifs42;
	int motifs43;
	int motifs44;
	int motifs45;
	int motifs46;
	int motifs47;

	motifs31 = CountMotif31();
	DumpVisitedMotif3List("motifs31.txt");
	motifs32 = CountMotif32();
	DumpVisitedMotif3List("motifs32.txt");
	motifs33 = CountMotif33();
	DumpVisitedMotif3List("motifs33.txt");
	motifs34 = CountMotif34();
	DumpVisitedMotif3List("motifs34.txt");
	motifs35 = CountMotif35();
	DumpVisitedMotif3List("motifs35.txt");
	motifs36 = CountMotif36();
	DumpVisitedMotif3List("motifs36.txt");
	motifs41 = CountMotif41();
	DumpVisitedMotif3List("motifs41.txt");
	motifs42 = CountMotif42();
	DumpVisitedMotif3List("motifs42.txt");
	motifs43 = CountMotif43();
	DumpVisitedMotif3List("motifs43.txt");
	motifs44 = CountMotif44();
	DumpVisitedMotif3List("motifs44.txt");
	motifs45 = CountMotif45();
	DumpVisitedMotif3List("motifs45.txt");
	motifs46 = CountMotif46();
	DumpVisitedMotif3List("motifs46.txt");
	motifs47 = CountMotif47();
	DumpVisitedMotif3List("motifs47.txt");

	out.open("motifs3.htm");
	out << "<html><body><table>";

	out << "<tr><td>" << motifs31 << "</td><td>" << motifs32 << "</td><td>" << motifs33 << "</td><td>" << motifs34 << "</td><td>" << motifs35 << "</td><td>" << motifs36 << "</td></tr>" << endl;

	out << "</table></body></html>";
	
	out.close();

	AfxMessageBox("Done30!");
}


int CountMotif31()
{
	MOTIF3* tempNode;
	int count = 0;

	tempNode = Motif3List;

	while (tempNode)
	{
		if ((strcmp(tempNode->effect1, "0")) &&
			(strcmp(tempNode->effect2, "0")) &&
			(strcmp(tempNode->effect3, "0")) &&
			(((tempNode->direction1 == 1) && 
			  (tempNode->direction2 == 1) &&
			  (tempNode->direction3 == -1)) ||
			  ((tempNode->direction1 == 1) && 
			  (tempNode->direction2 == -1) &&
			  (tempNode->direction3 == 1)) ||
			  ((tempNode->direction1 == -1) && 
			  (tempNode->direction2 == 1) &&
			  (tempNode->direction3 == 1))))
		{
			count += tempNode->count;
		}
		tempNode = tempNode->next;
	}
	return count;
}

int CountMotif32()
{
	MOTIF3* tempNode;
	int count = 0;

	tempNode = Motif3List;

	while (tempNode)
	{
		if ((!strcmp(tempNode->effect1, "0")) &&
			(!strcmp(tempNode->effect2, "0")) &&
			(!strcmp(tempNode->effect3, "0"))) 
		{
			count += tempNode->count;
		}
		tempNode = tempNode->next;
	}
	return count;
}

int CountMotif33()
{
	MOTIF3* tempNode;
	int count = 0;

	tempNode = Motif3List;

	while (tempNode)
	{
		if ((strcmp(tempNode->effect1, "0")) &&
			(strcmp(tempNode->effect2, "0")) &&
			(strcmp(tempNode->effect3, "0")) &&
			(((tempNode->direction1 == 1) && 
			  (tempNode->direction2 == 1) &&
			  (tempNode->direction3 == 1)) ||
			  ((tempNode->direction1 == -1) && 
			  (tempNode->direction2 == -1) &&
			  (tempNode->direction3 == -1))))
		{
			count += tempNode->count;
		}
		tempNode = tempNode->next;
	}
	return count;
}

int CountMotif34()
{
	return 0;
}

int CountMotif35()
{
	return 0;
}

int CountMotif36()
{
	return 0;
}
//feedforward
int CountMotif41()
{
	MOTIF4* tempNode;
	int count = 0;

	tempNode = Motif4List;

	while (tempNode)
	{
		tempNode->visited = 0;

		if ((((!strcmp(tempNode->effect1, "+")) || (!strcmp(tempNode->effect1, "_"))) &&
			((!strcmp(tempNode->effect2, "+")) || (!strcmp(tempNode->effect2, "_"))) &&
			((!strcmp(tempNode->effect3, "+")) || (!strcmp(tempNode->effect3, "_"))) &&
			((!strcmp(tempNode->effect4, "+")) || (!strcmp(tempNode->effect4, "_")))) &&
			(((tempNode->direction1 == 1) &&
			  (tempNode->direction2 == -1) &&
			  (tempNode->direction3 == 1) &&
			  (tempNode->direction4 == -1)) ||
			  ((tempNode->direction1 == -1) &&
			  (tempNode->direction2 == 1) &&
			  (tempNode->direction3 == -1) &&
			  (tempNode->direction4 == 1))))
		{
			count += tempNode->count;
		}
		tempNode = tempNode->next;
	}
	return count;
}

int CountMotif42()
{
	MOTIF4* tempNode;
	int count = 0;

	tempNode = Motif4List;

	while (tempNode)
	{
		tempNode->visited = 0;

		if ((((!strcmp(tempNode->effect1, "+")) || (!strcmp(tempNode->effect1, "_"))) &&
			((!strcmp(tempNode->effect2, "+")) || (!strcmp(tempNode->effect2, "_"))) &&
			((!strcmp(tempNode->effect3, "+")) || (!strcmp(tempNode->effect3, "_"))) &&
			((!strcmp(tempNode->effect4, "+")) || (!strcmp(tempNode->effect4, "_")))) &&
			(((tempNode->direction1 == 1) &&
			  (tempNode->direction2 == 1) &&
			  (tempNode->direction3 == -1) &&
			  (tempNode->direction4 == -1)) ||
			  ((tempNode->direction1 == -1) &&
			  (tempNode->direction2 == 1) &&
			  (tempNode->direction3 == 1) &&
			  (tempNode->direction4 == -1)) ||
			  ((tempNode->direction1 == -1) &&
			  (tempNode->direction2 == -1) &&
			  (tempNode->direction3 == 1) &&
			  (tempNode->direction4 == 1)) ||
			  ((tempNode->direction1 == 1) &&
			  (tempNode->direction2 == -1) &&
			  (tempNode->direction3 == -1) &&
			  (tempNode->direction4 == 1))))
		{
			count += tempNode->count;
		}
		tempNode = tempNode->next;
	}
	return count;
}

int CountMotif43()
{
	MOTIF4* tempNode;
	int count = 0;

	tempNode = Motif4List;

	while (tempNode)
	{
		tempNode->visited = 0;

		if ((((!strcmp(tempNode->effect1, "+")) || (!strcmp(tempNode->effect1, "_"))) &&
			((!strcmp(tempNode->effect2, "+")) || (!strcmp(tempNode->effect2, "_"))) &&
			((!strcmp(tempNode->effect3, "+")) || (!strcmp(tempNode->effect3, "_"))) &&
			((!strcmp(tempNode->effect4, "+")) || (!strcmp(tempNode->effect4, "_")))) &&
			(((tempNode->direction1 == 1) &&
			  (tempNode->direction2 == 1) &&
			  (tempNode->direction3 == 1) &&
			  (tempNode->direction4 == 1)) ||
			  ((tempNode->direction1 == -1) &&
			  (tempNode->direction2 == -1) &&
			  (tempNode->direction3 == -1) &&
			  (tempNode->direction4 == -1))))
		{
			count += tempNode->count;
		}
		tempNode = tempNode->next;
	}
	return count;
}

int CountMotif44()
{
	return 0;
}

int CountMotif45()
{
	return 0;
}
int CountMotif46()
{
	return 0;
}
int CountMotif47()
{
	return 0;
}

int CountMotif51()
{
	MOTIF5* tempNode;
	int count = 0;

	tempNode = Motif5List;

	while (tempNode)
	{
		tempNode->visited = 0;

		if ((((!strcmp(tempNode->effect1, "+")) || (!strcmp(tempNode->effect1, "_"))) &&
			((!strcmp(tempNode->effect2, "+")) || (!strcmp(tempNode->effect2, "_"))) &&
			((!strcmp(tempNode->effect3, "+")) || (!strcmp(tempNode->effect3, "_"))) &&
			((!strcmp(tempNode->effect4, "+")) || (!strcmp(tempNode->effect4, "_"))) &&
			((!strcmp(tempNode->effect5, "+")) || (!strcmp(tempNode->effect5, "_")))) &&
			(((tempNode->direction1 == 1) &&
			  (tempNode->direction2 == -1) &&
			  (tempNode->direction3 == 1) &&
			  (tempNode->direction4 == -1) &&
			  (tempNode->direction5 == -1)) ||
			  ((tempNode->direction1 == -1) &&
			  (tempNode->direction2 == 1) &&
			  (tempNode->direction3 == -1) &&
			  (tempNode->direction4 == 1) &&
			  (tempNode->direction5 == -1)) ||
			  ((tempNode->direction1 == -1) &&
			  (tempNode->direction2 == -1) &&
			  (tempNode->direction3 == 1) &&
			  (tempNode->direction4 == -1) &&
			  (tempNode->direction5 == 1)) ||
			  ((tempNode->direction1 == 1) &&
			  (tempNode->direction2 == -1) &&
			  (tempNode->direction3 == -1) &&
			  (tempNode->direction4 == 1) &&
			  (tempNode->direction5 == -1)) ||
			  ((tempNode->direction1 == -1) &&
			  (tempNode->direction2 == 1) &&
			  (tempNode->direction3 == -1) &&
			  (tempNode->direction4 == -1) &&
			  (tempNode->direction5 == 1))))
		{
			count += tempNode->count;
		}
		tempNode = tempNode->next;
	}
	return count;
}

int CountMotif53()
{
	MOTIF5* tempNode;
	int count = 0;

	tempNode = Motif5List;

	while (tempNode)
	{
		tempNode->visited = 0;

		if ((((!strcmp(tempNode->effect1, "+")) || (!strcmp(tempNode->effect1, "_"))) &&
			((!strcmp(tempNode->effect2, "+")) || (!strcmp(tempNode->effect2, "_"))) &&
			((!strcmp(tempNode->effect3, "+")) || (!strcmp(tempNode->effect3, "_"))) &&
			((!strcmp(tempNode->effect4, "+")) || (!strcmp(tempNode->effect4, "_"))) &&
			((!strcmp(tempNode->effect5, "+")) || (!strcmp(tempNode->effect5, "_")))) &&
			(((tempNode->direction1 == 1) &&
			  (tempNode->direction2 == 1) &&
			  (tempNode->direction3 == 1) &&
			  (tempNode->direction4 == 1) &&
			  (tempNode->direction5 == 1)) ||
			  ((tempNode->direction1 == -1) &&
			  (tempNode->direction2 == -1) &&
			  (tempNode->direction3 == -1) &&
			  (tempNode->direction4 == -1) &&
			  (tempNode->direction5 == -1))))
		{
			count += tempNode->count;
		}
		tempNode = tempNode->next;
	}
	return count;
}

void DumpVisitedMotif3List(char* fileName)
{
	MOTIF3* tempNode;
	ofstream out;

	out.open(fileName);
	
	tempNode = Motif3List;

	while (tempNode)
	{
		if (tempNode->visited)
		{
			out << tempNode->name1 << " " << tempNode->typeOfInteraction1 << " " << tempNode->effect1 << " " << tempNode->name2 << " " << tempNode->typeOfInteraction2 << " ";
			out << tempNode->effect2 << " " << tempNode->name3 << " " << tempNode->typeOfInteraction3 << " " << tempNode->effect3 << tempNode->count <<  endl;
		}
		tempNode = tempNode->next;
	}

	out.close();

	return;
}

void FreeMotifs(void)
{
	MOTIF3* temp3Node1;
	MOTIF4* temp4Node1;
	MOTIF5* temp5Node1;
	MOTIF3* temp3Node2;
	MOTIF4* temp4Node2;
	MOTIF5* temp5Node2;
	
	temp3Node1 = Motif3List;
	Motif3List = 0;
	Total3Names = 0;
	NumberOfMotif3 = 0;

	while (temp3Node1)
	{
		temp3Node2 = temp3Node1;
		temp3Node1 = temp3Node1->next;
		free(temp3Node2);
	}

	temp4Node1 = Motif4List;
	Motif4List = 0;
	Total4Names = 0;
	NumberOfMotif4 = 0;

	while (temp4Node1)
	{
		temp4Node2 = temp4Node1;
		temp4Node1 = temp4Node1->next;
		free(temp4Node2);
	}

	temp5Node1 = Motif5List;
	Motif5List = 0;

	while (temp5Node1)
	{
		temp5Node2 = temp5Node1;
		temp5Node1 = temp5Node1->next;
		free(temp5Node2);
	}
	return;
}
void CTestSVGDlg::OnBnClickedButton28()
{
	//AnalyzeSubNetworks("NE_and_BDNF_sub_nets_stats.htm", 2, 15, "NE_and_BDNF_sub_net_depth");
	//AnalyzeSubNetworks("GLUTAMATE_and_NE_sub_nets_stats.htm", 2, 15, "GLUTAMATE_and_NE_sub_net_depth");
	//AnalyzeSubNetworks("GLUTAMATE_and_BDNF_sub_nets_stats.htm", 2, 15, "GLUTAMATE_and_BDNF_sub_net_depth");
	AnalyzeSubNetworks("CREB_sub_nets_stats.htm", 2, 15, "CREB_sub_net_depth");
	AnalyzeSubNetworks("GLUTAMATE1_sub_nets_stats.htm", 2, 15, "GLUTAMATE_sub_net_depth");
	AnalyzeSubNetworks("NE1_sub_nets_stats.htm", 2, 15, "NE_sub_net_depth");
	AnalyzeSubNetworks("BDNF1_sub_nets_stats.htm", 2, 15, "BDNF_sub_net_depth");
	AnalyzeSubNetworks("FASL1_sub_nets_stats.htm", 2, 15, "FASL_sub_net_depth");
	AnalyzeSubNetworks("ALL_AT_ONCE_sub_nets_stats.htm", 2, 15, "ALL_AT_ONCE_sub_net_depth");

	AfxMessageBox("Done31!");
}

void CTestSVGDlg::OnBnClickedButton29()
{
	MOLECULE* tempNode;
	ofstream out;
	ofstream out1;
	int negatives = 0;
	int positives = 0;
	int listSoFar[20];
	int i;
	char fileName[200];

	out.open("GSK3_pathways_count.htm");

	out << "<html><body><table>" << endl;
	out << "<tr><td>Name</td><td>Positives</td><td>Negatives</td><tr>" << endl;

	for (i = 6; i <= 6; i++)
	{
		tempNode = MoleculesList;

		while (tempNode)
		{
			if (!strcmp(tempNode->name, "BAFF"))
			{
				negatives = 0;
				positives = 0;
				listSoFar[0] = tempNode->number;
				strcpy(fileName, "BAFF_TO_");
				strcat(fileName, tempNode->name);
				strcat(fileName, ".sig");
				out1.open(fileName);
				ClearInteractionsFlag();
				IndexOfGlobalList = 0;
				CountNumberOfPathwaysToOutputAndDump(out1, "NFKB", tempNode, i, 1, listSoFar, positives, negatives);
				AddInteractionsForFeedbackLoops(out1);
				out1.close();
				out << "<tr><td>" << tempNode->name << "</td><td>" << positives << "</td><td>" << negatives << "</td></tr>" << endl;
			}
			tempNode = tempNode->next;
		}
	}

	AfxMessageBox("Done32!");
}

int CountAllInteractionsFlags(void)
{
	INTERACTION* tempNode1;
	int count = 0;

	tempNode1 = InteractionsList;

	while (tempNode1)
	{
		if (tempNode1->flag)
		{
			count++;	
		}

		tempNode1 = tempNode1->next;
	}
		
	return count;
}
void CTestSVGDlg::TurnOnAllButtons()
{
	CButton* pButtonViewer = (CButton*) GetDlgItem(IDC_BUTTON_VIEWER);
	pButtonViewer->EnableWindow(1);

	CButton* pButtonCreateWebSite = (CButton*) GetDlgItem(IDC_BUTTON_CREATE_WEB_SITE);
	pButtonCreateWebSite->EnableWindow(1);

	CButton* myButton;

	myButton = (CButton*) GetDlgItem(IDC_BUTTON_GENE_LIST);
	myButton->EnableWindow(1);

	myButton = (CButton*) GetDlgItem(IDC_BUTTON_MOTIFS_INPUT);
	myButton->EnableWindow(1);

	myButton = (CButton*) GetDlgItem(IDC_BUTTON_VALIDATE);
	myButton->EnableWindow(1);

	myButton = (CButton*) GetDlgItem(IDC_BUTTON15);
	myButton->EnableWindow(1);

	myButton = (CButton*) GetDlgItem(IDC_BUTTON_NET);
	myButton->EnableWindow(1);

	myButton = (CButton*) GetDlgItem(IDC_BUTTON19);
	myButton->EnableWindow(1);

	myButton = (CButton*) GetDlgItem(IDC_BUTTON_CREATE_AND_DRAW_PATHWAYS);
	myButton->EnableWindow(1);

	myButton = (CButton*) GetDlgItem(IDC_BUTTON_GENERATE_PATHWAY);
	myButton->EnableWindow(1);

	myButton = (CButton*) GetDlgItem(IDC_BUTTON_MOTIFS);
	myButton->EnableWindow(1);

	CProgressCtrl* pProg = (CProgressCtrl*) GetDlgItem(IDC_PROGRESS);
	pProg->SetPos(0);

	CButton* pButtonSaveAs = (CButton*) GetDlgItem(IDC_BUTTON_SAVE_AS);
	pButtonSaveAs->EnableWindow(1);

	CButton* pButtonBasedOnConnectivity = (CButton*) GetDlgItem(IDC_BUTTON_BASED_ON_CONNECTIVITY);
	pButtonBasedOnConnectivity->EnableWindow(1);

	CButton* pButtonFromSourceNodes = (CButton*) GetDlgItem(IDC_BUTTON_FROM_SOURCE_NODES);
	pButtonFromSourceNodes->EnableWindow(1);

	CButton* pButtonInteractionsMatrix = (CButton*) GetDlgItem(IDC_BUTTON_INTERACTION_MATRIX);
	pButtonInteractionsMatrix->EnableWindow(1);

	CButton* pButtonShuffledNetworks = (CButton*) GetDlgItem(IDC_BUTTON_SHUFFLED_NETWORKS);
	pButtonShuffledNetworks->EnableWindow(1);

	CButton* pButtonComputeStats = (CButton*) GetDlgItem(IDC_BUTTON_CREATE_WEB_SITE2);
	pButtonComputeStats->EnableWindow(1);

	CButton* pButtonSif = (CButton*) GetDlgItem(IDC_BUTTON_SIF);
	pButtonSif->EnableWindow(1);

	CButton* pLoadNetwork = (CButton*) GetDlgItem(IDC_BUTTON_LOAD_NETWORK);
		pLoadNetwork->EnableWindow(1);

	myButton = (CButton*) GetDlgItem(IDC_BUTTON_LOAD_TWO_COLUMN);
		myButton->EnableWindow(1);

}
void CTestSVGDlg::ShutOffAllButtons()
{
	// adjust the progress bar based on the global
		CProgressCtrl* pProg = (CProgressCtrl*) GetDlgItem(IDC_PROGRESS);
		pProg->SetRange(0, NumberOfMolecules);
		pProg->SetPos(0);

		ProgressCount2 = 0;

		CButton* pButtonCreateWebSite = (CButton*) GetDlgItem(IDC_BUTTON_CREATE_WEB_SITE);
		pButtonCreateWebSite->EnableWindow(0);

		CButton* pLoadNetwork = (CButton*) GetDlgItem(IDC_BUTTON_LOAD_NETWORK);
		pLoadNetwork->EnableWindow(0);

		CButton* myButton;

		myButton = (CButton*) GetDlgItem(IDC_BUTTON_MOTIFS_INPUT);
		myButton->EnableWindow(0);

		myButton = (CButton*) GetDlgItem(IDC_BUTTON_VALIDATE);
		myButton->EnableWindow(0);

		myButton = (CButton*) GetDlgItem(IDC_BUTTON15);
		myButton->EnableWindow(0);

		myButton = (CButton*) GetDlgItem(IDC_BUTTON_NET);
		myButton->EnableWindow(0);

		myButton = (CButton*) GetDlgItem(IDC_BUTTON19);
		myButton->EnableWindow(0);

		myButton = (CButton*) GetDlgItem(IDC_BUTTON_CREATE_AND_DRAW_PATHWAYS);
		myButton->EnableWindow(0);

		myButton = (CButton*) GetDlgItem(IDC_BUTTON_GENERATE_PATHWAY);
		myButton->EnableWindow(0);

		myButton = (CButton*) GetDlgItem(IDC_BUTTON_LOAD_TWO_COLUMN);
		myButton->EnableWindow(0);

		CButton* pButtonLoadNetwork = (CButton*) GetDlgItem(IDC_BUTTON_GENE_LIST);
		pButtonLoadNetwork->EnableWindow(0);

		myButton = (CButton*) GetDlgItem(IDC_BUTTON_MOTIFS);
		myButton->EnableWindow(0);

		CButton* pButtonSaveAs = (CButton*) GetDlgItem(IDC_BUTTON_SAVE_AS);
		pButtonSaveAs->EnableWindow(0);

		CButton* pButtonViewer = (CButton*) GetDlgItem(IDC_BUTTON_VIEWER);
		pButtonSaveAs->EnableWindow(0);

		CButton* pButtonBasedOnConnectivity = (CButton*) GetDlgItem(IDC_BUTTON_BASED_ON_CONNECTIVITY);
		pButtonBasedOnConnectivity->EnableWindow(0);

		CButton* pButtonFromSourceNodes = (CButton*) GetDlgItem(IDC_BUTTON_FROM_SOURCE_NODES);
		pButtonFromSourceNodes->EnableWindow(0);

		CButton* pButtonInteractionsMatrix = (CButton*) GetDlgItem(IDC_BUTTON_INTERACTION_MATRIX);
		pButtonInteractionsMatrix->EnableWindow(0);

		CButton* pButtonShuffledNetworks = (CButton*) GetDlgItem(IDC_BUTTON_SHUFFLED_NETWORKS);
		pButtonShuffledNetworks->EnableWindow(0);

		CButton* pButtonComputeStats = (CButton*) GetDlgItem(IDC_BUTTON_CREATE_WEB_SITE2);
		pButtonComputeStats->EnableWindow(0);

		CButton* pButtonSif = (CButton*) GetDlgItem(IDC_BUTTON_SIF);
		pButtonSif->EnableWindow(0);
}

void CTestSVGDlg::OnBnClickedButtonCreateAndDrawPathways()
{
	CDialogPathwayGeneratorSetup myDialog;

	if (myDialog.DoModal() == IDOK)
	{
		PathwayGeneratorSetupStruct.maxSize = myDialog.m_maxSize;
		PathwayGeneratorSetupStruct.numberOfSteps = myDialog.m_numberOfSteps;
		PathwayGeneratorSetupStruct.sourceCondName1 = myDialog.m_sourceCondName1;
		PathwayGeneratorSetupStruct.sourceCondName2 = myDialog.m_sourceCondName2;
		PathwayGeneratorSetupStruct.sourceCondName3 = myDialog.m_sourceCondName3;
		PathwayGeneratorSetupStruct.sourceCondName4 = myDialog.m_sourceCondName4;
		PathwayGeneratorSetupStruct.sourceCondType1 = myDialog.m_sourceCondType1;
		PathwayGeneratorSetupStruct.sourceCondType2 = myDialog.m_sourceCondType2;
		PathwayGeneratorSetupStruct.sourceCondType3 = myDialog.m_sourceCondType3;
		PathwayGeneratorSetupStruct.sourceCondType4 = myDialog.m_sourceCondType4;
		PathwayGeneratorSetupStruct.targetCondName1 = myDialog.m_targetCondName1;
		PathwayGeneratorSetupStruct.targetCondName2 = myDialog.m_targetCondName2;
		PathwayGeneratorSetupStruct.targetCondName3 = myDialog.m_targetCondName3;
		PathwayGeneratorSetupStruct.targetCondName4 = myDialog.m_targetCondName4;
		PathwayGeneratorSetupStruct.targetCondType1 = myDialog.m_targetCondType1;
		PathwayGeneratorSetupStruct.targetCondType2 = myDialog.m_targetCondType2;
		PathwayGeneratorSetupStruct.targetCondType3 = myDialog.m_targetCondType3;
		PathwayGeneratorSetupStruct.targetCondType4 = myDialog.m_targetCondType4;
		PathwayGeneratorSetupStruct.directOnly = myDialog.m_checkDirectOnly;
		ShutOffAllButtons();

		if (DirLevel == 0)
		{
			DirLevel = 1;
		}
		else
		{
			chdir("..");	
		}
		mkdir("SNAVI_pg");
		chdir("SNAVI_pg");

		// start the thread that computes 
		pThreadCreateWebSite = AfxBeginThread(CreateAllPathwaysThread,
								GetSafeHwnd(), 
								THREAD_PRIORITY_NORMAL);
	}
	else
	{
		return;
	}
}

UINT CreateAllPathwaysThread(LPVOID pParam)
{
	MOLECULE* tempNode;
	MOLECULE* tempNode1;
	ofstream out;
	ofstream out1;
	int negatives = 0;
	int positives = 0;
	int listSoFar[20];
	int i;
	int count;
	char fileName[200];
	char sigFileName[200];
	char* mapNames[2000];
	int numberOfMapNames = 0;
	int steps;
	int bestStep;
	
	
	tempNode = MoleculesList;

	while (tempNode)
	{
		ProgressCount2++;
		if (CheckSourceCondition(tempNode)) //(!strcmp(tempNode->moleculeType, "Ligand")) || (!strcmp(tempNode->moleculeType, "Source")))
		{
			strcpy(GlobalSource, tempNode->name);
			tempNode1 = MoleculesList;
			while (tempNode1)
			{
				if (CheckTargetCondition(tempNode1))
				{
					strcpy(GlobalTarget, tempNode1->name);

					count = 0;
					steps = 2;
					GlobalSteps = 2;
					
					::PostMessage((HWND) pParam, WM_UPDATEALLPATHWAYSPROGRESS, 0, 0);

					while (count < PathwayGeneratorSetupStruct.maxSize)
					{
						GlobalSteps = steps;
						::PostMessage((HWND) pParam, WM_UPDATEALLPATHWAYSPROGRESS, 0, 0);

						negatives = 0;
						positives = 0;
						listSoFar[0] = tempNode->number;
						strcpy(fileName, tempNode->name);
						strcat(fileName, "_TO_");
						strcat(fileName, tempNode1->name);
						strcpy(sigFileName, fileName);
						strcat(sigFileName, ".sig");
						out1.open(sigFileName);
						ClearVisitedFlagForAllMolecules();
						ClearInteractionsFlag();
						IndexOfGlobalList = 0;
						CountNumberOfPathwaysToOutputAndDump(out1, tempNode1->name, tempNode, steps, 1, listSoFar, positives, negatives);
						AddInteractionsForFeedbackLoops(out1);
						count = CountAllInteractionsFlags();
						out1.close();
						if (count > PathwayGeneratorSetupStruct.maxSize)
						{
							out1.open(sigFileName);
							ClearVisitedFlagForAllMolecules();
							ClearInteractionsFlag();
							IndexOfGlobalList = 0;
							CountNumberOfPathwaysToOutputAndDump(out1, tempNode1->name, tempNode, bestStep, 1, listSoFar, positives, negatives);
							AddInteractionsForFeedbackLoops(out1);
							count = CountAllInteractionsFlags();
							out1.close();
							MakeSVGMapBasedOnVisited(fileName);
							mapNames[numberOfMapNames] = (char*) malloc(100);
							strcpy(mapNames[numberOfMapNames], fileName);
							numberOfMapNames++;
							count = 10000;
						} 
						else if (steps >= PathwayGeneratorSetupStruct.numberOfSteps)
						{	
							//not pathway was found
							break;
						}
						else 
						{
							bestStep = steps;
							count = 0;
							steps++;
						}
					}
				}
				tempNode1 = tempNode1->next;
			}
		}
		tempNode = tempNode->next;
	}

	ProgressCount = NumberOfMolecules;
	::PostMessage((HWND) pParam, WM_UPDATEALLPATHWAYSPROGRESS, 0, 0);

	if (numberOfMapNames != 0)
	{
		FailedToGeneratePathway = 0;

		CreatePathwaysWebpages(numberOfMapNames, mapNames);

		CreatePathwayGeneratorForm(numberOfMapNames, mapNames);
	

		for (i = 0; i < numberOfMapNames; i++)
		{
			free(mapNames[i]);
		}
	}
	else
	{
		FailedToGeneratePathway = 1;
	}

	::PostMessage((HWND) pParam, WM_THREADALLPATHWAYSFINISHED, 0, 0);

	return 0;
}

void CTestSVGDlg::OnBnClickedButtonValidate()
{
	ofstream validation;
	
	validation.open("validation.htm");

	validation << "<html><body>" << endl;
	CheckSameNameSourceTarget(validation);
	CheckSameNameDiferentACC(validation);
	CheckSameACCDifferentName(validation);
	CheckNonMammalianACC(validation);
	ListAllTypes(validation);
	CheckSameNameDifferentType(validation);
	CheckSameNameDifferentLocation(validation);
	CheckSamePairDifferentEffectOrInteraction(validation);
	CheckSamePairDifferentOrder(validation);
	CheckIfExpressedInNeurons(validation);
	
	validation << "</body></html>";
	validation.close();
	

	StartViewer("validation.htm");
	strcpy(LastViewerCall, "validation.htm");

}

void CheckSameNameSourceTarget(ofstream &validation)
{
	INTERACTION* tempNode;
	int flag = 0;

	tempNode = InteractionsList;

	while (tempNode)
	{
		if (!strcmp(tempNode->source, tempNode->target))
		{
			validation << "The following interaction has " << tempNode->source << " as both the source and target!<br>" << endl;
		}
		tempNode = tempNode->next;
	}

	if (flag == 0)
	{
		validation << "There are no interactions with the same source and target.<br>" << endl;
	}

	validation << "<br>" << endl;

	return;
}
void CheckSameNameDiferentACC(ofstream &validation)
{
	INTERACTION* tempNode1;
	INTERACTION* tempNode2;
	int flag = 0;

	tempNode1 = InteractionsList;

	while (tempNode1)
	{
			tempNode2 = InteractionsList;
			
			while (tempNode2)
			{
				if ((!strcmp(tempNode1->source, tempNode2->source))
					&&
				   ((strcmp(tempNode1->sourceAccHuman, tempNode2->sourceAccHuman)) ||
				   
				   (strcmp(tempNode1->sourceAccMouse, tempNode2->sourceAccMouse))))
				{
					validation << tempNode1->source << " have different accession code in the " << tempNode1->source << " " << tempNode1->target;
					validation << " interaction (" << tempNode1->sourceAccHuman << ") compared to " << tempNode2->source << " " <<  tempNode2->target;
					validation << " interaction (" << tempNode2->sourceAccHuman << ") interaction.<br><br>" << endl;
					flag = 1;
				}
				if ((!strcmp(tempNode1->source, tempNode2->target))
					&&
				   ((strcmp(tempNode1->sourceAccHuman, tempNode2->targetAccHuman)) || 
				   (strcmp(tempNode1->sourceAccMouse, tempNode2->targetAccMouse))))
				{
					validation << tempNode1->source << " have different accession code in the " << tempNode1->source << " " << tempNode1->target;
					validation << " interaction (" << tempNode1->sourceAccHuman << ") compared to " << tempNode2->source << " " <<  tempNode2->target;
					validation << " interaction (" << tempNode2->sourceAccHuman << ") interaction.<br><br>" << endl;
					flag = 1;
				}
				if ((!strcmp(tempNode1->target, tempNode2->target))
					&&
				   ((strcmp(tempNode1->targetAccHuman, tempNode2->targetAccHuman)) ||
				   (strcmp(tempNode1->targetAccMouse, tempNode2->targetAccMouse))))
				{
					validation << tempNode1->target << " have different accession code in the " << tempNode1->source << " " << tempNode1->target;
					validation << " interaction (" << tempNode1->targetAccHuman << ") compared to " << tempNode2->source << " " <<  tempNode2->target;
					validation << " interaction (" << tempNode2->targetAccHuman << ") interaction.<br><br>" << endl;
					flag = 1;
				}
				if ((!strcmp(tempNode1->target, tempNode2->source))
					&&
				   ((strcmp(tempNode1->targetAccHuman, tempNode2->sourceAccHuman)) ||
				   (strcmp(tempNode1->targetAccMouse, tempNode2->sourceAccMouse))))
				{
					validation << tempNode1->target << " have different accession code in the " << tempNode1->source << " " << tempNode1->target;
					validation << " interaction (" << tempNode1->targetAccHuman << ") compared to " << tempNode2->source << " " <<  tempNode2->target;
					validation << " interaction (" << tempNode2->targetAccHuman << ") interaction.<br><br>" << endl;
					flag = 1;
				}
				tempNode2 = tempNode2->next;
			}
			tempNode1 = tempNode1->next;
	}

	if (flag == 0)
	{
		validation << "No conflicts regarding different accession codes and the same name.<br><br>" << endl;
	}
}
void CheckSameACCDifferentName(ofstream &validation)
{
}
void CheckNonMammalianACC(ofstream &validation)
{
}
void ListAllTypes(ofstream &validation)
{
}
void CheckSameNameDifferentType(ofstream &validation)
{
}
void CheckSameNameDifferentLocation(ofstream &validation)
{
}
void CheckSamePairDifferentEffectOrInteraction(ofstream &validation)
{
	INTERACTION* tempInt1;
	INTERACTION* tempInt2;
	int flag = 0;

	tempInt1 = InteractionsList;

	while (tempInt1)
	{
		tempInt2 = InteractionsList;

		while (tempInt2)
		{
			if (((!strcmp(tempInt1->source, tempInt2->source))
				&&
				(!strcmp(tempInt1->target, tempInt2->target)))
				&&
				((strcmp(tempInt1->effect, tempInt2->effect)) ||
				 (strcmp(tempInt1->typeOfInteraction, tempInt2->typeOfInteraction))))
			{
				validation << "The effect of the interaction between " << tempInt1->source << " " << tempInt1->target;
				validation << " is different " << tempInt1->effect << " and " << tempInt2->effect << ".<br><br>"; 	
				flag = 1;
			}
			tempInt2 = tempInt2->next;
		}
		tempInt1 = tempInt1->next;	
	}

	if (flag == 0)
	{
		validation << "The are no interactions with the same source and target and different effect of type of interaction.<br><br>" << endl;
	}
}

void CheckSamePairDifferentOrder(ofstream &validation)
{
	INTERACTION* tempInt1;
	INTERACTION* tempInt2;
	int flag = 0;

	tempInt1 = InteractionsList;

	while (tempInt1)
	{
		tempInt2 = InteractionsList;

		while (tempInt2)
		{
			if ((!strcmp(tempInt1->source, tempInt2->target))
				&&
				(!strcmp(tempInt1->target, tempInt2->source)))
			{
				validation << "The interaction between " << tempInt1->source << " and " << tempInt1->target;
				validation << " has the source being the target and the target being the source.<br>";
				flag = 1;
			}
			tempInt2 = tempInt2->next;
		}

		tempInt1 = tempInt1->next;
	}

	if (flag == 0)
	{
		validation << "There are no cases where the source and the target are in opposite places.<br>" << endl;
	}
}
void CheckIfExpressedInNeurons(ofstream &validation)
{
}

void CTestSVGDlg::OnBnClickedButton5()
{
	return;

}

int GetNumberOfReferences(void)
{
	INTERACTION* tempNode;
	int numOfReferences = 0;
	
	int i, j;
	int flag;

	tempNode = InteractionsList;

	while (tempNode)
	{
		for (i = 0; i < tempNode->referenceCount; i++)
		{
			flag = 0;
			for (j = 0; j < numOfReferences; j++)
			{
				if (tempNode->references[i] == pubMedIds[j])
				{
					flag = 1;
				}
			}
			if (!flag)
			{
				pubMedIds[numOfReferences] = tempNode->references[i];
				numOfReferences++;
			}
		}	
		tempNode = tempNode->next;
	}
	return numOfReferences;
}

// WriteDIB		- Writes a DIB to file
// Returns		- TRUE on success
// szFile		- Name of file to write to
// hDIB			- Handle of the DIB
BOOL WriteDIB( LPTSTR szFile, HANDLE hDIB)
{
	BITMAPFILEHEADER	hdr;
	LPBITMAPINFOHEADER	lpbi;

	if (!hDIB)
		return FALSE;

	CFile file;
	if( !file.Open( szFile, CFile::modeWrite|CFile::modeCreate) )
		return FALSE;

	lpbi = (LPBITMAPINFOHEADER)hDIB;

	int nColors = 1 << lpbi->biBitCount;

	// Fill in the fields of the file header 
	hdr.bfType		= ((WORD) ('M' << 8) | 'B');	// is always "BM"
	hdr.bfSize		= GlobalSize (hDIB) + sizeof( hdr );
	hdr.bfReserved1 	= 0;
	hdr.bfReserved2 	= 0;
	hdr.bfOffBits		= (DWORD) (sizeof( hdr ) + lpbi->biSize +
						nColors * sizeof(RGBQUAD));

	// Write the file header 
	file.Write( &hdr, sizeof(hdr) );

	// Write the DIB header and the bits 
	file.Write( lpbi, GlobalSize(hDIB) );

	return TRUE;
}

BOOL WriteWindowToDIB( LPTSTR szFile, CDC *pDC )
{
	CBitmap 	bitmap;
	CDC 		memDC;
	CRect		rect;


	memDC.CreateCompatibleDC(pDC); 

	//pWnd->GetWindowRect(rect);


	bitmap.CreateCompatibleBitmap(pDC, 1000, 500);
	
	CBitmap* pOldBitmap = memDC.SelectObject(&bitmap);
	//memDC.BitBlt(0, 0, rect.Width(),rect.Height(), &dc, 0, 0, SRCCOPY); 
	memDC.BitBlt(0, 0, 1000, 500, pDC, 0, 0, SRCCOPY);

	// Create logical palette if device support a palette
	CPalette pal;
	if( pDC->GetDeviceCaps(RASTERCAPS) & RC_PALETTE )
	{
		UINT nSize = sizeof(LOGPALETTE) + (sizeof(PALETTEENTRY) * 256);
		LOGPALETTE *pLP = (LOGPALETTE *) new BYTE[nSize];
		pLP->palVersion = 0x300;

		pLP->palNumEntries = 
			GetSystemPaletteEntries( *pDC, 0, 255, pLP->palPalEntry );

		// Create the palette
		pal.CreatePalette( pLP );

		delete[] pLP;
	}

	memDC.SelectObject(pOldBitmap);

	// Convert the bitmap to a DIB
	HANDLE hDIB = DDBToDIB( bitmap, BI_RGB, &pal );

	if( hDIB == NULL )
		return FALSE;

	// Write it to file
	WriteDIB( szFile, hDIB );

	// Free the memory allocated by DDBToDIB for the DIB
	GlobalFree( hDIB );
	return TRUE;
}

HBITMAP DIBToDDB( HANDLE hDIB )
{
	LPBITMAPINFOHEADER	lpbi;
	HBITMAP 		hbm;
	CPalette		pal;
	CPalette*		pOldPal;
	CClientDC		dc(NULL);
	int i;

	if (hDIB == NULL)
		return NULL;

	lpbi = (LPBITMAPINFOHEADER)hDIB;

	int nColors = lpbi->biClrUsed ? lpbi->biClrUsed : 
						1 << lpbi->biBitCount;

	BITMAPINFO &bmInfo = *(LPBITMAPINFO)hDIB ;
	LPVOID lpDIBBits;
	if( bmInfo.bmiHeader.biBitCount > 8 )
		lpDIBBits = (LPVOID)((LPDWORD)(bmInfo.bmiColors + 
			bmInfo.bmiHeader.biClrUsed) + 
			((bmInfo.bmiHeader.biCompression == BI_BITFIELDS) ? 3 : 0));
	else
		lpDIBBits = (LPVOID)(bmInfo.bmiColors + nColors);

	// Create and select a logical palette if needed
	if( nColors <= 256 && dc.GetDeviceCaps(RASTERCAPS) & RC_PALETTE)
	{
		UINT nSize = sizeof(LOGPALETTE) + (sizeof(PALETTEENTRY) * nColors);
		LOGPALETTE *pLP = (LOGPALETTE *) new BYTE[nSize];

		pLP->palVersion = 0x300;
		pLP->palNumEntries = nColors;

		for(i = 0; i < nColors; i++)
		{
			pLP->palPalEntry[i].peRed = bmInfo.bmiColors[i].rgbRed;
			pLP->palPalEntry[i].peGreen = bmInfo.bmiColors[i].rgbGreen;
			pLP->palPalEntry[i].peBlue = bmInfo.bmiColors[i].rgbBlue;
			pLP->palPalEntry[i].peFlags = 0;
		}

		pal.CreatePalette( pLP );

		delete[] pLP;

		// Select and realize the palette
		pOldPal = dc.SelectPalette( &pal, FALSE );
		dc.RealizePalette();
	}

	
	hbm = CreateDIBitmap(dc.GetSafeHdc(),		// handle to device context
			(LPBITMAPINFOHEADER)lpbi,	// pointer to bitmap info header 
			(LONG)CBM_INIT,			// initialization flag
			lpDIBBits,			// pointer to initialization data 
			(LPBITMAPINFO)lpbi,		// pointer to bitmap info
			DIB_RGB_COLORS );		// color-data usage 

	if (pal.GetSafeHandle())
		dc.SelectPalette(pOldPal,FALSE);

	return hbm;
}

// DDBToDIB		- Creates a DIB from a DDB
// bitmap		- Device dependent bitmap
// dwCompression	- Type of compression - see BITMAPINFOHEADER
// pPal			- Logical palette
HANDLE DDBToDIB( CBitmap& bitmap, DWORD dwCompression, CPalette* pPal ) 
{
	BITMAP			bm;
	BITMAPINFOHEADER	bi;
	LPBITMAPINFOHEADER 	lpbi;
	DWORD			dwLen;
	HANDLE			hDIB;
	HANDLE			handle;
	HDC 			hDC;
	HPALETTE		hPal;


	ASSERT( bitmap.GetSafeHandle() );

	// The function has no arg for bitfields
	if( dwCompression == BI_BITFIELDS )
		return NULL;

	// If a palette has not been supplied use defaul palette
	hPal = (HPALETTE) pPal->GetSafeHandle();
	if (hPal==NULL)
		hPal = (HPALETTE) GetStockObject(DEFAULT_PALETTE);

	// Get bitmap information
	bitmap.GetObject(sizeof(bm),(LPSTR)&bm);

	// Initialize the bitmapinfoheader
	bi.biSize		= sizeof(BITMAPINFOHEADER);
	bi.biWidth		= bm.bmWidth;
	bi.biHeight 		= bm.bmHeight;
	bi.biPlanes 		= 1;
	bi.biBitCount		= bm.bmPlanes * bm.bmBitsPixel;
	bi.biCompression	= dwCompression;
	bi.biSizeImage		= 0;
	bi.biXPelsPerMeter	= 0;
	bi.biYPelsPerMeter	= 0;
	bi.biClrUsed		= 0;
	bi.biClrImportant	= 0;

	// Compute the size of the  infoheader and the color table
	int nColors = (1 << bi.biBitCount);
	if( nColors > 256 ) 
		nColors = 0;
	dwLen  = bi.biSize + nColors * sizeof(RGBQUAD);

	// We need a device context to get the DIB from
	hDC = GetDC(NULL);
	hPal = SelectPalette(hDC,hPal,FALSE);
	RealizePalette(hDC);

	// Allocate enough memory to hold bitmapinfoheader and color table
	hDIB = GlobalAlloc(GMEM_FIXED,dwLen);

	if (!hDIB){
		SelectPalette(hDC,hPal,FALSE);
		ReleaseDC(NULL,hDC);
		return NULL;
	}

	lpbi = (LPBITMAPINFOHEADER)hDIB;

	*lpbi = bi;

	// Call GetDIBits with a NULL lpBits param, so the device driver 
	// will calculate the biSizeImage field 
	GetDIBits(hDC, (HBITMAP)bitmap.GetSafeHandle(), 0L, (DWORD)bi.biHeight,
			(LPBYTE)NULL, (LPBITMAPINFO)lpbi, (DWORD)DIB_RGB_COLORS);

	bi = *lpbi;

	// If the driver did not fill in the biSizeImage field, then compute it
	// Each scan line of the image is aligned on a DWORD (32bit) boundary
	if (bi.biSizeImage == 0){
		bi.biSizeImage = ((((bi.biWidth * bi.biBitCount) + 31) & ~31) / 8) 
						* bi.biHeight;

		// If a compression scheme is used the result may infact be larger
		// Increase the size to account for this.
		if (dwCompression != BI_RGB)
			bi.biSizeImage = (bi.biSizeImage * 3) / 2;
	}

	// Realloc the buffer so that it can hold all the bits
	dwLen += bi.biSizeImage;
	if (handle = GlobalReAlloc(hDIB, dwLen, GMEM_MOVEABLE))
		hDIB = handle;
	else{
		GlobalFree(hDIB);

		// Reselect the original palette
		SelectPalette(hDC,hPal,FALSE);
		ReleaseDC(NULL,hDC);
		return NULL;
	}

	// Get the bitmap bits
	lpbi = (LPBITMAPINFOHEADER)hDIB;

	// FINALLY get the DIB
	BOOL bGotBits = GetDIBits( hDC, (HBITMAP)bitmap.GetSafeHandle(),
				0L,				// Start scan line
				(DWORD)bi.biHeight,		// # of scan lines
				(LPBYTE)lpbi 			// address for bitmap bits
				+ (bi.biSize + nColors * sizeof(RGBQUAD)),
				(LPBITMAPINFO)lpbi,		// address of bitmapinfo
				(DWORD)DIB_RGB_COLORS);		// Use RGB for color table

	if( !bGotBits )
	{
		GlobalFree(hDIB);
		
		SelectPalette(hDC,hPal,FALSE);
		ReleaseDC(NULL,hDC);
		return NULL;
	}

	SelectPalette(hDC,hPal,FALSE);
	ReleaseDC(NULL,hDC);
	return hDIB;
}

void CTestSVGDlg::DrawImageInMemory(int column, int* string, int stringSize, CDC* dcMemory)
{
	CPen myPen;
	int i;
	POINT pt;
	

	pt.x = column * 5 + 10;
	pt.y = 10;

	dcMemory->MoveTo(pt.x, pt.y);
	dcMemoryImage.MoveTo(pt.x, pt.y);

	for (i = 0; i < stringSize; i++)
	{
		if (string[i] == 0)
		{
			myPen.CreatePen(PS_SOLID, 2, RGB(140, 180, 255));
			
		}
		else if (string[i] == 1) 
		{
			myPen.CreatePen(PS_SOLID, 2, RGB(140, 255, 180));
		}
		else if (string[i] == 2)
		{
			myPen.CreatePen(PS_SOLID, 2, RGB(255, 255, 0));
		}
		else if (string[i] == 3)
		{
			myPen.CreatePen(PS_SOLID, 2, RGB(255, 155, 0));
		}
		else if (string[i] == 4)
		{
			myPen.CreatePen(PS_SOLID, 2, RGB(255, 0, 0));
		}
		dcMemory->SelectObject( &myPen );
		dcMemory->Rectangle(pt.x, pt.y, pt.x + 3, pt.y - 3);
		
		myPen.DeleteObject();
		pt.y = pt.y + 5;
	}
}

void DumpToJpegTopMotif3(char* fileName)
{
	MOTIF3* tempNode;
	int i = 30000;
	CString graphString;
	char tempName[100];

	tempNode = Motif3List;

	while (tempNode)
	{
		graphString = "";
		graphString = "digraph G {";
		graphString += "size=\"8,8\";";
		graphString += "concentrate=false;\n";

		graphString += " { ";
		graphString +=  tempNode->name1;
		graphString += "1";
		graphString += " [style=\"filled\", label=\"";
		graphString +=  tempNode->name1;
		graphString += "\" shape=\"";
		graphString += GetShape(tempNode->name1);
		graphString += "\", color=\"";
		graphString += GetColor(tempNode->name1);
		graphString += "\"];\n";

		graphString +=  tempNode->name2;
		graphString += "2";
		graphString += " [style=\"filled\", label=\"";
		graphString +=  tempNode->name2;
		graphString += "\" shape=\"";
		graphString += GetShape(tempNode->name2);
		graphString += "\", color=\"";
		graphString += GetColor(tempNode->name2);
		graphString += "\"];\n";

		graphString +=  tempNode->name3;
		graphString += "3";
		graphString += " [style=\"filled\", label=\"";
		graphString +=  tempNode->name3;
		graphString += "\" shape=\"";
		graphString += GetShape(tempNode->name3);
		graphString += "\", color=\"";
		graphString += GetColor(tempNode->name3);
		graphString += "\"];\n";
		graphString += " } \n";
	
		if (tempNode->direction1 == 1)
		{
			graphString +=  tempNode->name1;
			graphString +=  "1 -> ";
			graphString +=  tempNode->name2;
			graphString +=  "2";
		}
		else
		{
			graphString +=  tempNode->name2;
			graphString +=  "2 -> ";
			graphString +=  tempNode->name1;
			graphString +=  "1";
		}
		if (!strcmp(tempNode->effect1, "+"))
		{
			graphString += " [arrowhead=\"normal\", color=\"darkgreen\"] ";
		}
		else if (!strcmp(tempNode->effect1, "_"))
		{
			graphString += " [arrowhead=\"tee\",arrowsize=\"3.0\", color=\"red1\"] ";
		}
		else if (!strcmp(tempNode->effect1, "0"))
		{
			graphString += " [arrowhead=\"box\",arrowtail=\"box\", color=\"blue1\"] ";
		}
		graphString +=  ";";

		if (tempNode->direction2 == 1)
		{
			graphString +=  tempNode->name2;
			graphString +=  "2 -> ";
			graphString +=  tempNode->name3;
			graphString +=  "3";
		}
		else
		{
			graphString +=  tempNode->name3;
			graphString +=  "3 -> ";
			graphString +=  tempNode->name2;
			graphString +=  "2";
		}
		if (!strcmp(tempNode->effect2, "+"))
		{
			graphString += " [arrowhead=\"normal\", color=\"darkgreen\"] ";
		}
		else if (!strcmp(tempNode->effect2, "_"))
		{
			graphString += " [arrowhead=\"tee\",arrowsize=\"3.0\", color=\"red1\"] ";
		}
		else if (!strcmp(tempNode->effect2, "0"))
		{
			graphString += " [arrowhead=\"box\",arrowtail=\"box\", color=\"blue1\"] ";
		}
		graphString +=  ";";

		if (tempNode->direction3 == 1)
		{
			graphString +=  tempNode->name3;
			graphString +=  "3 -> ";
			graphString +=  tempNode->name1;
			graphString +=  "1";
		}
		else
		{
			graphString +=  tempNode->name1;
			graphString +=  "1 -> ";
			graphString +=  tempNode->name3;
			graphString +=  "3";
		}

		if (!strcmp(tempNode->effect3, "+"))
		{
			graphString += " [arrowhead=\"normal\", color=\"darkgreen\"] ";
		}
		else if (!strcmp(tempNode->effect3, "_"))
		{
			graphString += " [arrowhead=\"tee\",arrowsize=\"3.0\", color=\"red1\"] ";
		}
		else if (!strcmp(tempNode->effect3, "0"))
		{
			graphString += " [arrowhead=\"box\",arrowtail=\"box\", color=\"blue1\"] ";
		}
		graphString +=  ";";
		
		graphString += "}";

		tempName[0] = 0;
		sprintf(tempName, "%s_%d", fileName, i+1);
		DumpStringToJPEG(graphString, tempName);
		//DumpStringToSVG(graphString, tempName, 0, 0);
		i++;
		tempNode = tempNode->next;
	}
}
void DumpToJpegTopMotif4(char* fileName)
{
	MOTIF4* tempNode;
	int i = 40000;
	CString graphString;
	char tempName[100];

	tempNode = Motif4List;

	while (tempNode)
	{
		graphString = "";
		graphString = "digraph G {";
		graphString += "size=\"5,5\";";
		graphString += "concentrate=false;\n";

		graphString += " { ";
		graphString +=  tempNode->name1;
		graphString += "1";
		graphString += " [style=\"filled\", label=\"";
		graphString +=  tempNode->name1;
		graphString += "\" shape=\"";
		graphString += GetShape(tempNode->name1);
		graphString += "\", color=\"";
		graphString += GetColor(tempNode->name1);
		graphString += "\"];\n";

		graphString +=  tempNode->name2;
		graphString += "2";
		graphString += " [style=\"filled\", label=\"";
		graphString +=  tempNode->name2;
		graphString += "\" shape=\"";
		graphString += GetShape(tempNode->name2);
		graphString += "\", color=\"";
		graphString += GetColor(tempNode->name2);
		graphString += "\"];\n";

		graphString +=  tempNode->name3;
		graphString += "3";
		graphString += " [style=\"filled\", label=\"";
		graphString +=  tempNode->name3;
		graphString += "\" shape=\"";
		graphString += GetShape(tempNode->name3);
		graphString += "\", color=\"";
		graphString += GetColor(tempNode->name3);
		graphString += "\"];\n";

		graphString +=  tempNode->name4;
		graphString += "4";
		graphString += " [style=\"filled\", label=\"";
		graphString +=  tempNode->name4;
		graphString += "\" shape=\"";
		graphString += GetShape(tempNode->name4);
		graphString += "\", color=\"";
		graphString += GetColor(tempNode->name4);
		graphString += "\"];\n";

		graphString += " } \n";
	
		if (tempNode->direction1 == 1)
		{
			graphString +=  tempNode->name1;
			graphString +=  "1 -> ";
			graphString +=  tempNode->name2;
			graphString +=  "2";
		}
		else
		{
			graphString +=  tempNode->name2;
			graphString +=  "2 -> ";
			graphString +=  tempNode->name1;
			graphString +=  "1";
		}
		if (!strcmp(tempNode->effect1, "+"))
		{
			graphString += " [arrowhead=\"normal\", color=\"darkgreen\"] ";
		}
		else if (!strcmp(tempNode->effect1, "_"))
		{
			graphString += " [arrowhead=\"tee\",arrowsize=\"3.0\", color=\"red1\"] ";
		}
		else if (!strcmp(tempNode->effect1, "0"))
		{
			graphString += " [arrowhead=\"box\",arrowtail=\"box\", color=\"blue1\"] ";
		}
		graphString +=  ";";

		if (tempNode->direction2 == 1)
		{
			graphString +=  tempNode->name2;
			graphString +=  "2 -> ";
			graphString +=  tempNode->name3;
			graphString +=  "3";
		}
		else
		{
			graphString +=  tempNode->name3;
			graphString +=  "3 -> ";
			graphString +=  tempNode->name2;
			graphString +=  "2";
		}
		if (!strcmp(tempNode->effect2, "+"))
		{
			graphString += " [arrowhead=\"normal\", color=\"darkgreen\"] ";
		}
		else if (!strcmp(tempNode->effect2, "_"))
		{
			graphString += " [arrowhead=\"tee\",arrowsize=\"3.0\", color=\"red1\"] ";
		}
		else if (!strcmp(tempNode->effect2, "0"))
		{
			graphString += " [arrowhead=\"box\",arrowtail=\"box\", color=\"blue1\"] ";
		}
		graphString +=  ";";

		if (tempNode->direction3 == 1)
		{
			graphString +=  tempNode->name3;
			graphString +=  "3 -> ";
			graphString +=  tempNode->name4;
			graphString +=  "4";
		}
		else
		{
			graphString +=  tempNode->name4;
			graphString +=  "4 -> ";
			graphString +=  tempNode->name3;
			graphString +=  "3";
		}

		if (!strcmp(tempNode->effect3, "+"))
		{
			graphString += " [arrowhead=\"normal\", color=\"darkgreen\"] ";
		}
		else if (!strcmp(tempNode->effect3, "_"))
		{
			graphString += " [arrowhead=\"tee\",arrowsize=\"3.0\", color=\"red1\"] ";
		}
		else if (!strcmp(tempNode->effect3, "0"))
		{
			graphString += " [arrowhead=\"box\",arrowtail=\"box\", color=\"blue1\"] ";
		}
		graphString +=  ";";

		if (tempNode->direction4 == 1)
		{
			graphString +=  tempNode->name4;
			graphString +=  "4 -> ";
			graphString +=  tempNode->name1;
			graphString +=  "1";
		}
		else
		{
			graphString +=  tempNode->name1;
			graphString +=  "1 -> ";
			graphString +=  tempNode->name4;
			graphString +=  "4";
		}

		if (!strcmp(tempNode->effect4, "+"))
		{
			graphString += " [arrowhead=\"normal\", color=\"darkgreen\"] ";
		}
		else if (!strcmp(tempNode->effect4, "_"))
		{
			graphString += " [arrowhead=\"tee\",arrowsize=\"3.0\", color=\"red1\"] ";
		}
		else if (!strcmp(tempNode->effect4, "0"))
		{
			graphString += " [arrowhead=\"box\",arrowtail=\"box\", color=\"blue1\"] ";
		}
		graphString +=  ";";
		
		graphString += "}";

		sprintf(tempName, "%s_%d", fileName, i+1);
		DumpStringToJPEG(graphString, tempName);
		//DumpStringToSVG(graphString, tempName, 0, 0);
		
		i++;
		tempNode = tempNode->next;
	}
}
void DumpToJpegTopMotif5(void)
{
	MOTIF5* tempNode;
	int i = 0;
	CString graphString;
	char fileName[100];

	tempNode = Motif5List;

	while (tempNode)
	{
		graphString = "";
		graphString = "digraph G {";
		graphString += "size=\"8,8\";";
		graphString += "concentrate=false;\n";

		graphString += " { ";
		graphString +=  tempNode->name1;
		graphString += "1";
		graphString += " [style=\"filled\", label=\"";
		graphString +=  tempNode->name1;
		graphString += "\" shape=\"";
		graphString += GetShape(tempNode->name1);
		graphString += "\", color=\"";
		graphString += GetColor(tempNode->name1);
		graphString += "\"];\n";

		graphString +=  tempNode->name2;
		graphString += "2";
		graphString += " [style=\"filled\", label=\"";
		graphString +=  tempNode->name2;
		graphString += "\" shape=\"";
		graphString += GetShape(tempNode->name2);
		graphString += "\", color=\"";
		graphString += GetColor(tempNode->name2);
		graphString += "\"];\n";

		graphString +=  tempNode->name3;
		graphString += "3";
		graphString += " [style=\"filled\", label=\"";
		graphString +=  tempNode->name3;
		graphString += "\" shape=\"";
		graphString += GetShape(tempNode->name3);
		graphString += "\", color=\"";
		graphString += GetColor(tempNode->name3);
		graphString += "\"];\n";

		graphString +=  tempNode->name4;
		graphString += "4";
		graphString += " [style=\"filled\", label=\"";
		graphString +=  tempNode->name4;
		graphString += "\" shape=\"";
		graphString += GetShape(tempNode->name4);
		graphString += "\", color=\"";
		graphString += GetColor(tempNode->name4);
		graphString += "\"];\n";

		graphString +=  tempNode->name5;
		graphString += "5";
		graphString += " [style=\"filled\", label=\"";
		graphString +=  tempNode->name5;
		graphString += "\" shape=\"";
		graphString += GetShape(tempNode->name5);
		graphString += "\", color=\"";
		graphString += GetColor(tempNode->name5);
		graphString += "\"];\n";

		graphString += " } \n";
	
		if (tempNode->direction1 == 1)
		{
			graphString +=  tempNode->name1;
			graphString +=  "1 -> ";
			graphString +=  tempNode->name2;
			graphString +=  "2";
		}
		else
		{
			graphString +=  tempNode->name2;
			graphString +=  "2 -> ";
			graphString +=  tempNode->name1;
			graphString +=  "1";
		}
		if (!strcmp(tempNode->effect1, "+"))
		{
			graphString += " [arrowhead=\"normal\", color=\"darkgreen\"] ";
		}
		else if (!strcmp(tempNode->effect1, "_"))
		{
			graphString += " [arrowhead=\"tee\",arrowsize=\"3.0\", color=\"red1\"] ";
		}
		else if (!strcmp(tempNode->effect1, "0"))
		{
			graphString += " [arrowhead=\"box\",arrowtail=\"box\", color=\"blue1\"] ";
		}
		graphString +=  ";";

		if (tempNode->direction2 == 1)
		{
			graphString +=  tempNode->name2;
			graphString +=  "2 -> ";
			graphString +=  tempNode->name3;
			graphString +=  "3";
		}
		else
		{
			graphString +=  tempNode->name3;
			graphString +=  "3 -> ";
			graphString +=  tempNode->name2;
			graphString +=  "2";
		}
		if (!strcmp(tempNode->effect2, "+"))
		{
			graphString += " [arrowhead=\"normal\", color=\"darkgreen\"] ";
		}
		else if (!strcmp(tempNode->effect2, "_"))
		{
			graphString += " [arrowhead=\"tee\",arrowsize=\"3.0\", color=\"red1\"] ";
		}
		else if (!strcmp(tempNode->effect2, "0"))
		{
			graphString += " [arrowhead=\"box\",arrowtail=\"box\", color=\"blue1\"] ";
		}
		graphString +=  ";";

		if (tempNode->direction3 == 1)
		{
			graphString +=  tempNode->name3;
			graphString +=  "3 -> ";
			graphString +=  tempNode->name4;
			graphString +=  "4";
		}
		else
		{
			graphString +=  tempNode->name4;
			graphString +=  "4 -> ";
			graphString +=  tempNode->name3;
			graphString +=  "3";
		}

		if (!strcmp(tempNode->effect3, "+"))
		{
			graphString += " [arrowhead=\"normal\", color=\"darkgreen\"] ";
		}
		else if (!strcmp(tempNode->effect3, "_"))
		{
			graphString += " [arrowhead=\"tee\",arrowsize=\"3.0\", color=\"red1\"] ";
		}
		else if (!strcmp(tempNode->effect3, "0"))
		{
			graphString += " [arrowhead=\"box\",arrowtail=\"box\", color=\"blue1\"] ";
		}
		graphString +=  ";";

		if (tempNode->direction4 == 1)
		{
			graphString +=  tempNode->name4;
			graphString +=  "4 -> ";
			graphString +=  tempNode->name5;
			graphString +=  "5";
		}
		else
		{
			graphString +=  tempNode->name5;
			graphString +=  "5 -> ";
			graphString +=  tempNode->name4;
			graphString +=  "4";
		}

		if (!strcmp(tempNode->effect4, "+"))
		{
			graphString += " [arrowhead=\"normal\", color=\"darkgreen\"] ";
		}
		else if (!strcmp(tempNode->effect4, "_"))
		{
			graphString += " [arrowhead=\"tee\",arrowsize=\"3.0\", color=\"red1\"] ";
		}
		else if (!strcmp(tempNode->effect4, "0"))
		{
			graphString += " [arrowhead=\"box\",arrowtail=\"box\", color=\"blue1\"] ";
		}
		graphString +=  ";";

		if (tempNode->direction5 == 1)
		{
			graphString +=  tempNode->name5;
			graphString +=  "5 -> ";
			graphString +=  tempNode->name1;
			graphString +=  "1";
		}
		else
		{
			graphString +=  tempNode->name1;
			graphString +=  "1 -> ";
			graphString +=  tempNode->name5;
			graphString +=  "5";
		}

		if (!strcmp(tempNode->effect5, "+"))
		{
			graphString += " [arrowhead=\"normal\", color=\"darkgreen\"] ";
		}
		else if (!strcmp(tempNode->effect5, "_"))
		{
			graphString += " [arrowhead=\"tee\",arrowsize=\"3.0\", color=\"red1\"] ";
		}
		else if (!strcmp(tempNode->effect5, "0"))
		{
			graphString += " [arrowhead=\"box\",arrowtail=\"box\", color=\"blue1\"] ";
		}
		graphString +=  ";";
		
		graphString += "}";

		sprintf(fileName, "motif5_%d", i+1);
		DumpStringToJPEG(graphString, fileName);
		//DumpStringToSVG(graphString, fileName, 0, 0);
		tempNode = tempNode->next;
		i++;
		if (i == 18)
		{
			break;
		}
	}
}

void DumpFlaggedInteractionsToPajek(char* pajekFileName)
{
	//LoadMachines();
	ifstream connections;
    ofstream graph;
	MOLECULE* tempNode;
	MOLECULE* tempNode1;
	INTERACTION* tempInteraction;    
	graph.open(pajekFileName);
	char colorAndShape[100];
	char moleculeTypeIndex;
    
	//TakeOutTheHubs();
	
	graph << "*Vertices    " << NumberOfMolecules << endl;

	tempNode = MoleculesList;


	while (tempNode)
	{
		moleculeTypeIndex = GetMoleculeTypeIndex(tempNode->moleculeType);

		GetColorAndShape(moleculeTypeIndex, colorAndShape);

		if (tempNode->machine == TRANSMEMBRANE)
		{
			graph << tempNode->number << "  " << "\"" << tempNode->name << "\"" << "ic Orange ellipse" << endl;
		}
		else if (tempNode->machine == TRANSMISSION)
		{
			graph << tempNode->number << "  " << "\"" << tempNode->name << "\"" << " ic Goldenrod ellipse" << endl;
		}
		else if (tempNode->machine == TRANSLATION)
		{
			graph << tempNode->number << "  " << "\"" << tempNode->name << "\"" << " ic SkyBlue ellipse" << endl;
		}
		else if (tempNode->machine == TRANSCRIPTION)
		{
			graph << tempNode->number << "  " << "\"" << tempNode->name << "\"" << " ic LightGreen ellipse" << endl;
		}
		else if (tempNode->machine == SECRETION)
		{
			graph << tempNode->number << "  " << "\"" << tempNode->name << "\"" << " ic Orchid ellipse" << endl;
		}
		else if (tempNode->machine == CYTOSKELETON)
		{
			graph << tempNode->number << "  " << "\"" << tempNode->name << "\"" << " ic Periwinkle ellipse" << endl;
		}
		else if (tempNode->machine == APOPTOSIS)
		{
			graph << tempNode->number << "  " << "\"" << tempNode->name << "\"" << " ic Black ellipse" << endl;
		}
		else if (tempNode->machine == EXTRACELLULAR_LIGANDS)
		{
			graph << tempNode->number << "  " << "\"" << tempNode->name << "\"" << " ic White ellipse" << endl;
		}
		else
		{
			graph << tempNode->number << "  " << "\"" << tempNode->name << "\"" << " ic Blue ellipse" << endl;
		}

		
		tempNode = tempNode->next;
	}


	graph << "*Arcs" << endl;

	tempInteraction = InteractionsList;

	while (tempInteraction)
    { 
		if (tempInteraction->flag)
		{
			tempNode = GetNodeBasedOnName(tempInteraction->source);
			tempNode1 = GetNodeBasedOnName(tempInteraction->target);
			if (!strcmp(tempInteraction->effect, "+"))
			{
				graph << "   " << GetNumberBasedOnString(tempInteraction->source) << "    ";
				graph << GetNumberBasedOnString(tempInteraction->target) << "    " <<  "1 c Green" << endl;
				graph << "   " << GetNumberBasedOnString(tempInteraction->source) << "    ";
				graph << GetNumberBasedOnString(tempInteraction->target) << "    " <<  "1 c Green" << endl;
			}
			else if (!strcmp(tempInteraction->effect, "_"))
			{
				graph << "   " << GetNumberBasedOnString(tempInteraction->source) << "    ";
				graph << GetNumberBasedOnString(tempInteraction->target) << "    " <<  "1 c Orange" << endl;
				graph << "   " << GetNumberBasedOnString(tempInteraction->source) << "    ";
				graph << GetNumberBasedOnString(tempInteraction->target) << "    " <<  "1 c Orange" << endl;
			} 
			else 	if (!strcmp(tempInteraction->effect, "0"))
			{
				graph << "   " << GetNumberBasedOnString(tempInteraction->source) << "    ";
				graph << GetNumberBasedOnString(tempInteraction->target) << "    " <<  "1 c Blue" << endl;
			}
		
		}

		tempInteraction = tempInteraction->next;
	}
	graph.close();
	return;
}
void CTestSVGDlg::OnBnClickedButton30()
{
	int i;
	int j;
	int motifs31;
	int motifs32;
    int motifs33;
	int motifs41;
	int motifs42;
	int motifs43;
	int motifs51;
	int motifs53;
	char fileName[100];
	char name[100][100];
	int k = 0;
	MOLECULE* startNode;

	ofstream out;
	out.open("motifs_for_steps_networks.htm");
	out << "<html><body><table>";

	startNode = MoleculesList;

	/*
	while (startNode)
	{
		if (!strcmp(startNode->moleculeType, "TF"))
		{
			strcpy(name[k], startNode->name);
			k++;
		}
		startNode = startNode->next;
	}

	*/

	k = 0;
	strcpy(name[k], "CREB");
	k++;
	strcpy(name[k], "ELK1");
	k++;
	strcpy(name[k], "AP1");
	k++;
	strcpy(name[k], "ZIF268");
	k++;
	strcpy(name[k], "GLUTAMATE");
	k++;
	strcpy(name[k], "NE");
	k++;
	strcpy(name[k], "BDNF");
	k++;
	strcpy(name[k], "GLUTAMATE_and_NE");
	k++;
	strcpy(name[k], "GLUTAMATE_and_BDNF");
	k++;
	strcpy(name[k], "NE_and_BDNF");
	k++;
	strcpy(name[k], "GLUR1");
	k++;
	strcpy(name[k], "ARP23");
	k++;

	FreeNetwork();

	for (j = 0; j < k; j++)
	{
		out << "<TR><TD>" << name[j] << "</TD>";

		for (i = 2; i <= 8; i++)
		{	
			sprintf(fileName, "%s_sub_net_depth%d.sig", name[j], i);
			LoadNetwork(fileName);		
			CountDirectedCycles(3, 0);
			motifs31 = CountMotif31();
			motifs32 = CountMotif32();
			motifs33 = CountMotif33();
			motifs41 = CountMotif41();
			motifs42 = CountMotif42();
			motifs43 = CountMotif43();
			motifs51 = CountMotif51();
			motifs53 = CountMotif53();
				
			if (CountIslands() == 1)
			{
				out << "<td>" << i << "</td><td>" << NumberOfInteractions << "</td><td>" << NumberOfMolecules << "</td><td>" << ComputeCC() /* "na" */ << "</td><td>" << ComputeAvgPathLength() /* "na" */ << "</td><td>" << CountIslands() << "</td><td>" << motifs31 << "</td><td>" << motifs32 << "</td><td>" << motifs41 << "</td><td>" << motifs42 <<  "</td><td>" << motifs51 << "</td></tr>" << endl;
			}
			else
			{
				out << "<td>" << i << "</td><td>" << NumberOfInteractions << "</td><td>" << NumberOfMolecules << "</td><td>" << /* ComputeCC() */ "na" << "</td><td>" << "NA" << "</td><td>" << CountIslands() << "</td><td>" << motifs31 << "</td><td>" << motifs32 << "</td><td>" << motifs41 << "</td><td>" << motifs42 <<  "</td><td>" << motifs51 << "</td></tr>" << endl;
			}

			FreeMotifs();		
			FreeNetwork();
		}
	}
			
	out << "</TR>" << endl;	
	out << "</table></body></html>";
	
	out.close();

	AfxMessageBox("Done34!");
}


int These3NamesAlreadyBeenHere(char* name1, char* name2, char* name3)
{
	int i;
	int flag = 0;

	for (i = 0; i < Total3Names; i++)
	{
		if  (((!strcmp(Names1[i], name1)) || (!strcmp(Names1[i], name2)) || (!strcmp(Names1[i], name3))) &&
			((!strcmp(Names2[i], name1)) || (!strcmp(Names2[i], name2)) || (!strcmp(Names2[i], name3))) &&
			((!strcmp(Names3[i], name1)) || (!strcmp(Names3[i], name2)) || (!strcmp(Names3[i], name3))))

		{
			flag = 1;
		}
	}

	if (!flag)
	{
		strcpy(Names1[i], name1);
		strcpy(Names2[i], name2);
		strcpy(Names3[i], name3);
		Total3Names++;
	}

	return flag;
}
int These4NamesAlreadyBeenHere(char* name1, char* name2, char* name3, char* name4)
{
	int i;
	int flag = 0;

	for (i = 0; i < Total4Names; i++)
	{
		if (((!strcmp(Names1[i], name1)) || (!strcmp(Names1[i], name2)) || (!strcmp(Names1[i], name3)) || (!strcmp(Names1[i], name4))) &&
			((!strcmp(Names2[i], name1)) || (!strcmp(Names2[i], name2)) || (!strcmp(Names2[i], name3)) || (!strcmp(Names2[i], name4))) &&
			((!strcmp(Names3[i], name1)) || (!strcmp(Names3[i], name2)) || (!strcmp(Names3[i], name3)) || (!strcmp(Names3[i], name4))) &&
			((!strcmp(Names4[i], name1)) || (!strcmp(Names4[i], name2)) || (!strcmp(Names4[i], name3)) || (!strcmp(Names4[i], name4))))

		{
			flag = 1;
		}
	}

	if (!flag)
	{
		strcpy(Names1[i], name1);
		strcpy(Names2[i], name2);
		strcpy(Names3[i], name3);
		strcpy(Names4[i], name4);
		Total4Names++;
	}

	return flag;
}

int These5NamesAlreadyBeenHere(char* name1, char* name2, char* name3, char* name4, char* name5)
{
	int i;
	int flag = 0;

	for (i = 0; i < Total5Names; i++)
	{
		if (((!strcmp(Names1[i], name1)) || (!strcmp(Names1[i], name2)) || (!strcmp(Names1[i], name3)) || (!strcmp(Names1[i], name4)) || (!strcmp(Names1[i], name5))) &&
			((!strcmp(Names2[i], name1)) || (!strcmp(Names2[i], name2)) || (!strcmp(Names2[i], name3)) || (!strcmp(Names2[i], name4)) || (!strcmp(Names2[i], name5))) &&
			((!strcmp(Names3[i], name1)) || (!strcmp(Names3[i], name2)) || (!strcmp(Names3[i], name3)) || (!strcmp(Names3[i], name4)) || (!strcmp(Names3[i], name5))) &&
			((!strcmp(Names4[i], name1)) || (!strcmp(Names4[i], name2)) || (!strcmp(Names4[i], name3)) || (!strcmp(Names4[i], name4)) || (!strcmp(Names4[i], name5))) &&
			((!strcmp(Names5[i], name1)) || (!strcmp(Names5[i], name2)) || (!strcmp(Names5[i], name3)) || (!strcmp(Names5[i], name4)) || (!strcmp(Names5[i], name5))))

		{
			flag = 1;
		}
	}

	if (!flag)
	{
		strcpy(Names1[i], name1);
		strcpy(Names2[i], name2);
		strcpy(Names3[i], name3);
		strcpy(Names4[i], name4);
		strcpy(Names5[i], name5);
		Total4Names++;
	}

	return flag;
}

int AreThereInBetweenThese4Connections(char* name1, char* name2, char* name3, char* name4)
{
	MOLECULE* tempNode1;
	MOLECULE* tempNode2;
	int i;

	tempNode1 = GetNodeBasedOnName(name1);
	tempNode2 = GetNodeBasedOnName(name3);

	for (i = 0; i < tempNode1->linksCount; i++)
	{

		if (tempNode1->linksTo[i] == tempNode2->number)
		{
			return 1;
		}
	}

	tempNode1 = GetNodeBasedOnName(name2);
	tempNode2 = GetNodeBasedOnName(name4);

	for (i = 0; i < tempNode1->linksCount; i++)
	{

		if (tempNode1->linksTo[i] == tempNode2->number)
		{
			return 1;
		}
	}

	return 0;
}
int AreThereInBetweenThese5Connections(char* name1, char* name2, char* name3, char* name4, char* name5)
{
	MOLECULE* tempNode1;
	MOLECULE* tempNode2;
	int i;

	tempNode1 = GetNodeBasedOnName(name1);
	tempNode2 = GetNodeBasedOnName(name3);

	for (i = 0; i < tempNode1->linksCount; i++)
	{

		if (tempNode1->linksTo[i] == tempNode2->number)
		{
			return 1;
		}
	}

	tempNode1 = GetNodeBasedOnName(name1);
	tempNode2 = GetNodeBasedOnName(name4);

	for (i = 0; i < tempNode1->linksCount; i++)
	{

		if (tempNode1->linksTo[i] == tempNode2->number)
		{
			return 1;
		}
	}

	tempNode1 = GetNodeBasedOnName(name2);
	tempNode2 = GetNodeBasedOnName(name4);

	for (i = 0; i < tempNode1->linksCount; i++)
	{

		if (tempNode1->linksTo[i] == tempNode2->number)
		{
			return 1;
		}
	}

	tempNode1 = GetNodeBasedOnName(name2);
	tempNode2 = GetNodeBasedOnName(name5);

	for (i = 0; i < tempNode1->linksCount; i++)
	{

		if (tempNode1->linksTo[i] == tempNode2->number)
		{
			return 1;
		}
	}

	tempNode1 = GetNodeBasedOnName(name3);
	tempNode2 = GetNodeBasedOnName(name5);

	for (i = 0; i < tempNode1->linksCount; i++)
	{

		if (tempNode1->linksTo[i] == tempNode2->number)
		{
			return 1;
		}
	}

	return 0;
}
void CTestSVGDlg::OnBnClickedButtonGeneratePathway()
{
	CDialogPathwayGenerator myDialog;

	if (myDialog.DoModal() == IDOK)
	{
		PathwayGeneratorSetupStruct.maxSize = myDialog.m_maxSize;
		PathwayGeneratorSetupStruct.numberOfSteps = myDialog.m_numberOfSteps;
		PathwayGeneratorSetupStruct.sourceCondName1 = myDialog.m_sourceCondName1;
		PathwayGeneratorSetupStruct.sourceCondName2 = myDialog.m_sourceCondName2;
		PathwayGeneratorSetupStruct.sourceCondName3 = myDialog.m_sourceCondName3;
		PathwayGeneratorSetupStruct.sourceCondName4 = myDialog.m_sourceCondName4;
		PathwayGeneratorSetupStruct.sourceCondType1 = myDialog.m_sourceCondType1;
		PathwayGeneratorSetupStruct.sourceCondType2 = myDialog.m_sourceCondType2;
		PathwayGeneratorSetupStruct.sourceCondType3 = myDialog.m_sourceCondType3;
		PathwayGeneratorSetupStruct.sourceCondType4 = myDialog.m_sourceCondType4;
		PathwayGeneratorSetupStruct.targetCondName1 = myDialog.m_targetCondName1;
		PathwayGeneratorSetupStruct.targetCondName2 = myDialog.m_targetCondName2;
		PathwayGeneratorSetupStruct.targetCondName3 = myDialog.m_targetCondName3;
		PathwayGeneratorSetupStruct.targetCondName4 = myDialog.m_targetCondName4;
		PathwayGeneratorSetupStruct.targetCondType1 = myDialog.m_targetCondType1;
		PathwayGeneratorSetupStruct.targetCondType2 = myDialog.m_targetCondType2;
		PathwayGeneratorSetupStruct.targetCondType3 = myDialog.m_targetCondType3;
		PathwayGeneratorSetupStruct.targetCondType4 = myDialog.m_targetCondType4;

		ShutOffAllButtons();

		if (DirLevel == 0)
		{
			DirLevel = 1;
		}
		else
		{
			chdir("..");	
		}
		mkdir("SNAVI_pg");
		chdir("SNAVI_pg");

		// start the thread that computes 
		pThreadCreateWebSite = AfxBeginThread(CreateAllPathwaysThread,
								GetSafeHwnd(), 
								THREAD_PRIORITY_NORMAL);
	}
	else
	{
		return;
	}
}

int DownLoadAbstractInTextForPubMedID(int pubMedId)
{
	COleDateTime today = COleDateTime::GetCurrentTime();
	ifstream inlist;
	CString theString;
	LPTSTR strObject = new TCHAR[200];
	char tempStr[100];
	char dummy[100];
	ofstream temp;
	int dwRet;
    int count = 0;
	ofstream debug;
	size_t length;

	CInternetSession session("My Session");
	CHttpConnection* pServer = NULL;
	CHttpFile* pFile = NULL;
	CString strServerName = "eutils.ncbi.nlm.nih.gov";
	CString tempUrl;
	INTERNET_PORT nPort = 80;
	
	pServer = session.GetHttpConnection(strServerName, nPort);

	try
	{

		//http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=1521331&retmode=mode
		tempUrl.Format("http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=%d", pubMedId);
			
		tempUrl.Replace("http://eutils.ncbi.nlm.nih.gov", "");

		_tcscpy(strObject, tempUrl);
			
		pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject);
			
		pFile->AddRequestHeaders("test");
		
		pFile->SendRequest();
			
		dwRet = HTTP_STATUS_OK;
		 

		strcpy(tempStr, itoa(pubMedId, dummy, 10));

		strcat(tempStr, ".txt");

		if (dwRet == HTTP_STATUS_OK)
		{
			temp.open(tempStr);
				
			try 
			{
				int count = 0;
				while (pFile->ReadString(szBuff, 4096))
				{
						length = strlen(szBuff);
						szBuff[length] = 0;
						temp << szBuff << endl;
				}
			}
			catch (CInternetException* pEx)
			{
				return -1;
				//AfxMessageBox("You must be connected to the internet in order to download an update!");
			}
			temp.close();
		}

		delete pFile;
	}
	catch (CInternetException* pEx)
	{
		return -1;
		//AfxMessageBox("You must be connected to the internet in order to download an update!");
	}

	return 0;
}

void GetTitleScienceFormat(int pubMedId, CString& title)
{
    ifstream inputFile;
	char fileName[1000];
	char dummy[100];
	char temp[5000];
	CString tempStr = "";
	CString tempStr1 = "";
	int first;

	title = "";

	strcpy(fileName, itoa(pubMedId, dummy, 10));
	strcat(fileName, ".txt");

	inputFile.open(fileName);

	while (!inputFile.eof())
	{
		inputFile >> temp;

		if (!strcmp(temp, "title"))
		{
			inputFile >> temp;
			inputFile >> temp;

			if (!strcmp(temp, "name"))
			{
				first = 1;
				while (strcmp(temp, "}"))
				{
					inputFile >> temp;
					if (!strcmp(temp, "}"))
					{
						break;
					}
					else
					{
						if (first)
						{
							first = 0;
							tempStr = temp;
						}
						else
						{
							tempStr = tempStr + " " + temp;
						}
						tempStr.Replace("&quot;", "");
					}
				}
			}
		}
	}
	title = tempStr;

	inputFile.close();

	return;
}
void GetYearScienceFormat(int pubMedId, CString& year)
{
    ifstream inputFile;
	char fileName[1000];
	char dummy[100];
	char temp[5000];
	CString tempStr = "";

	year = "";

	strcpy(fileName, itoa(pubMedId, dummy, 10));
	strcat(fileName, ".txt");

	inputFile.open(fileName);

	while (!inputFile.eof())
	{
		inputFile >> temp;

		if (!strcmp(temp, "year"))
		{
			inputFile >> temp;
			year = temp;
			year.Replace(",", "");
			break;
		}
	}


	inputFile.close();

	return;
}

void DeletePubMedIdFile(int pubMedId)
{
	char fileName[1000];
	char dummy[10];

	fstream file;

	strcpy(fileName, itoa(pubMedId, dummy, 10));
	strcat(fileName, ".txt");

	DeleteFile(fileName);

	return;
}

void GetJournalScienceFormat(int pubMedId, CString& journal)
{
    ifstream inputFile;
	char fileName[1000];
	char dummy[100];
	char temp[5000];
	CString tempStr = "";
	int flag;
	

	journal = "";

	strcpy(fileName, itoa(pubMedId, dummy, 10));
	strcat(fileName, ".txt");

	inputFile.open(fileName);

	tempStr = "";

	while (!inputFile.eof())
	{
		inputFile >> temp;

		flag = 0;

		if (!strcmp(temp, "ml-jta"))
		{
			while ((strcmp(temp, ",")) && (!inputFile.eof()))
			{
				flag = 1;
				inputFile >> temp;
				if (!strcmp(temp, "issn"))
				{
					break;
				}
				tempStr += temp;
				tempStr.Replace("&quot;", "");
				tempStr.Replace(",", "");
				tempStr = tempStr + ". ";
			}

			if (flag)
			{
				break;
			}
		}

		if (flag)
		{
			break;
		}
	}

	journal = tempStr;

	inputFile.close();

	return;
}
void GetVolumeScienceFormat(int pubMedId, CString& volume)
{
    ifstream inputFile;
	char fileName[1000];
	char dummy[100];
	char temp[5000];
	CString tempStr = "";

	volume = "";

	strcpy(fileName, itoa(pubMedId, dummy, 10));
	strcat(fileName, ".txt");

	inputFile.open(fileName);

	while (!inputFile.eof())
	{
		inputFile >> temp;

		if (!strcmp(temp, "volume"))
		{
			inputFile >> temp;
			tempStr = temp;
			tempStr.Replace("&quot;", "");
			break;
		}
	}

	volume = tempStr;

	inputFile.close();

	return;
}
void GetPagesScienceFormat(int pubMedId, CString& pages)
{
    ifstream inputFile;
	char fileName[1000];
	char dummy[100];
	char temp[5000];
	CString tempStr = "";
	int i = 0;

	pages = "";

	strcpy(fileName, itoa(pubMedId, dummy, 10));
	strcat(fileName, ".txt");

	inputFile.open(fileName);

	while (!inputFile.eof())
	{
		inputFile >> temp;

		if (!strcmp(temp, "pages"))
		{
			inputFile >> temp;
			tempStr = temp;
			tempStr.Replace("&quot;", "");
			tempStr = tempStr.Tokenize("-", i);
			break;
		}
	}

	pages = tempStr;

	inputFile.close();

	return;
}

void GetAuthorScienceFormat(int pubMedId, CString& authors)
{
	ifstream inputFile;
	char fileName[1000];
	char dummy[100];
	char temp[5000];
	CString tempStr = "";
	int count = 0;
	int lastName = 1;
	CString tempLastName;
	authors = "";

	strcpy(fileName, itoa(pubMedId, dummy, 10));
	strcat(fileName, ".txt");

	inputFile.open(fileName);

	while (!inputFile.eof())
	{
		inputFile >> temp;

		if (!strcmp(temp, "authors"))
		{
			inputFile >> temp;
			inputFile >> temp;
			inputFile >> temp;
			inputFile >> temp;

			while (strcmp(temp, "},"))
			{
				inputFile >> temp;
				if (!strcmp(temp, "},"))
				{
					break;
				}
				else if (count == 4)
				{
					authors = authors + " et al., ";
					break;
				}
				else
				{

					tempStr = temp;
					tempStr.Replace("&quot;", "");
					if (lastName)
					{
						tempLastName = tempStr;
						lastName = 0;
						count++;
					}
					else
					{
						tempStr.Replace(",", "");

						if (tempStr.GetLength() == 1)
						{
							authors = authors + tempStr.GetBuffer()[0];
							authors = authors + ". " + tempLastName + ", ";
						}
						else if (tempStr.GetLength() == 2)
						{
							authors = authors + tempStr.GetBuffer()[0];
							authors = authors + ". ";
							authors = authors + tempStr.GetBuffer()[1];
							authors = authors + ". ";
							authors = authors + tempLastName + ", ";
						}
						else if (tempStr.GetLength() == 3)
						{
							authors = authors + tempStr.GetBuffer()[0];
							authors = authors + ". ";
							authors = authors + tempStr.GetBuffer()[1];
							authors = authors + ". ";
							authors = authors + tempStr.GetBuffer()[2];
							authors = authors + ". ";
							authors = authors + tempLastName + ", ";
						}
						lastName = 1;
					}
				}
			}
		}
	}

	inputFile.close();

	return;
}

void GetTitleARBFormat(int pubMedId, CString& title)
{
    ifstream inputFile;
	char fileName[1000];
	char dummy[100];
	char temp[5000];
	CString tempStr = "";
	CString tempStr1 = "";
	int first;

	title = "";

	strcpy(fileName, itoa(pubMedId, dummy, 10));
	strcat(fileName, ".txt");

	inputFile.open(fileName);

	while (!inputFile.eof())
	{
		inputFile >> temp;

		if (!strcmp(temp, "title"))
		{
			inputFile >> temp;
			inputFile >> temp;

			if (!strcmp(temp, "name"))
			{
				first = 1;
				while (strcmp(temp, "}"))
				{
					inputFile >> temp;
					if (!strcmp(temp, "}"))
					{
						break;
					}
					else
					{
						if (first)
						{
							first = 0;
							tempStr = temp;
						}
						else
						{
							tempStr = tempStr + " " + temp;
						}
						tempStr.Replace("&quot;", "");
					}
				}
			}
		}
	}
	title = tempStr;

	inputFile.close();

	return;
}
void GetYearARBFormat(int pubMedId, CString& year)
{
    ifstream inputFile;
	char fileName[1000];
	char dummy[100];
	char temp[5000];
	CString tempStr = "";

	year = "";

	strcpy(fileName, itoa(pubMedId, dummy, 10));
	strcat(fileName, ".txt");

	inputFile.open(fileName);

	while (!inputFile.eof())
	{
		inputFile >> temp;

		if (!strcmp(temp, "year"))
		{
			inputFile >> temp;
			year = temp;
		}
	}


	inputFile.close();

	return;
}
void GetJournalARBFormat(int pubMedId, CString& journal)
{
    ifstream inputFile;
	char fileName[1000];
	char dummy[100];
	char temp[5000];
	CString tempStr = "";
	int flag;

	journal = "";

	strcpy(fileName, itoa(pubMedId, dummy, 10));
	strcat(fileName, ".txt");

	inputFile.open(fileName);

	while (!inputFile.eof())
	{
		inputFile >> temp;

		flag = 0;

		if (!strcmp(temp, "ml-jta"))
		{
			flag = 1;

			while (strcmp(temp, ","))
			{
				inputFile >> temp;
				tempStr = temp;
				tempStr.Replace("&quot;", "");
				tempStr.Replace(",", "");
				break;
			}
		}

		if (flag)
		{
			break;
		}
	}

	journal = tempStr + ".";

	inputFile.close();

	return;
}
void GetVolumeARBFormat(int pubMedId, CString& volume)
{
    ifstream inputFile;
	char fileName[1000];
	char dummy[100];
	char temp[5000];
	CString tempStr = "";

	volume = "";

	strcpy(fileName, itoa(pubMedId, dummy, 10));
	strcat(fileName, ".txt");

	inputFile.open(fileName);

	while (!inputFile.eof())
	{
		inputFile >> temp;

		if (!strcmp(temp, "volume"))
		{
			inputFile >> temp;
			tempStr = temp;
			tempStr.Replace("&quot;", "");
		}
	}

	volume = tempStr;

	inputFile.close();

	return;
}
void GetPagesARBFormat(int pubMedId, CString& pages)
{
    ifstream inputFile;
	char fileName[1000];
	char dummy[100];
	char temp[5000];
	CString tempStr = "";

	pages = "";

	strcpy(fileName, itoa(pubMedId, dummy, 10));
	strcat(fileName, ".txt");

	inputFile.open(fileName);

	while (!inputFile.eof())
	{
		inputFile >> temp;

		if (!strcmp(temp, "pages"))
		{
			inputFile >> temp;
			tempStr = temp;
			tempStr.Replace("&quot;", "");
		}
	}

	pages = tempStr;

	inputFile.close();

	return;
}

void GetAuthorARBFormat(int pubMedId, CString& authors)
{
	ifstream inputFile;
	char fileName[1000];
	char dummy[100];
	char temp[5000];
	CString tempStr = "";
	int count = 0;

	authors = "";

	strcpy(fileName, itoa(pubMedId, dummy, 10));
	strcat(fileName, ".txt");

	inputFile.open(fileName);

	while (!inputFile.eof())
	{
		inputFile >> temp;

		if (!strcmp(temp, "authors"))
		{
			inputFile >> temp;
			inputFile >> temp;
			inputFile >> temp;
			inputFile >> temp;

			while (strcmp(temp, "}"))
			{
				inputFile >> temp;
				if (!strcmp(temp, "}"))
				{
					authors = authors + tempStr + ".";
					break;
				}
				else if (!strcmp(temp, ","))
				{
					authors = authors + tempStr + ", ";
					tempStr = "";
					count++;

					if (count == 5)
					{
						authors = authors + " et al.";
						break;
					}
				}
				else
				{
					tempStr = tempStr + " " + temp;
					tempStr.Replace("&quot;", "");
				}
			}
		}
	}

	inputFile.close();

	return;
}

//This function was implemeted by Sudar
double ComputeGC(void)
{
	MOLECULE *tempNode;
	MOLECULE *tempDegreeNode;
	MOLECULE *neighborNode;
	MOLECULE *thirdNode;
	double gc=0;
	bool prim=false;
	double tempQ;
	double tempZ;
	int primaryQuadsFound=0;
	int secondaryQuadsFound=0;
	int secondaryDegrees=0;
	int primaryDegrees=0;
	int i;

	tempNode=MoleculesList;

	while (tempNode)
	{
		for (i=0;i< tempNode->linksCount;i++)
		{
			tempQ=0;
			tempZ=0;
			neighborNode=GetNodeBasedOnNumber(tempNode->linksTo[i]);

			if (neighborNode)
			{
				for (int j=0;j<neighborNode->linksCount;j++)
				{	
					thirdNode=GetNodeBasedOnNumber(neighborNode->linksTo[j]);
					if ((!thirdNode) || (thirdNode->number==tempNode->number))
					{
					}
					else
					{
						for (int k=0;k<thirdNode->linksCount;k++)
						{
							for (int l=0;l<tempNode->linksCount;l++)
							{
								if (thirdNode->linksTo[k]==neighborNode->number)
								{
								}
								else
								{
									if (thirdNode->linksTo[k]==tempNode->linksTo[l])
									{
										for (int m=0;m<thirdNode->linksCount;m++)
										{
											if (thirdNode->linksTo[m]==tempNode->number)
											{
												primaryQuadsFound++;
												prim=true;
											}
										}
										if (!prim)
										{
											secondaryQuadsFound++;
										}
										prim=false;
									}
								}
							}
						}
					}
				}
			}
		}
		primaryDegrees=tempNode->linksCount;
		for (int n=0;n<tempNode->linksCount;n++)
		{
			tempDegreeNode=GetNodeBasedOnNumber(tempNode->linksTo[n]);
			if (tempDegreeNode)
			{
				secondaryDegrees+=tempDegreeNode->linksCount-1;
			}
			else
			{
				secondaryDegrees+= 0;
			}
		}
		tempQ=(double)(primaryQuadsFound+secondaryQuadsFound);
		tempQ/=2;
		tempZ=(double)(primaryDegrees*(primaryDegrees-1)*(primaryDegrees-2))/2;
		tempZ+=(double)(secondaryDegrees*primaryDegrees*(primaryDegrees-1))/2;
		if (tempQ>tempZ)
		{
			tempQ=tempQ;
			tempZ=tempZ;
		}
		if (tempZ>0)
		{
			gc+=(double)(tempQ/tempZ);
			tempNode->gc = (double)(tempQ/tempZ);
		}
		else
		{
			tempNode->gc = 0;
		}
		tempNode=tempNode->next;
		primaryQuadsFound=0;
		secondaryQuadsFound=0;
		primaryDegrees=0;
		secondaryDegrees=0;
	}
	double kval=double(NumberOfInteractions);
	kval/=double(NumberOfMolecules);
	gc=(double)(gc/NumberOfMolecules);
	return gc;
}

void CreatePathwaysWebpages(int numberOfMapNames, char* mapNames[])
{	
	ofstream out;
	ofstream out1;
	int negatives = 0;
	int positives = 0;
	int i;
	char fileName[200];
	char netFileName[200];
	CString node1Name;
	CString node2Name;
	int start = 0;
	FreeNetwork();

    for (i = 0; i < numberOfMapNames; i++)
	{
		strcpy(fileName, mapNames[i]);
		strcpy(netFileName, fileName);
		strcat(netFileName, ".sig");
		strcat(fileName, ".htm");
		out.open(fileName);
		LoadNetwork(netFileName);
		
		node1Name = mapNames[i];
		node2Name = mapNames[i];

		start = 0;
		node1Name = node2Name.Tokenize("_", start);
		node2Name.Tokenize("_", start);
		node2Name = node2Name.Tokenize("_", start);
		out << "<html><body>";			
		out << "<CENTER><H3>Connection map from ";
		out << "<a href=\"" << node1Name << ".htm\">" << node1Name << "</a>";
		out << " to ";
		out << "<a href=\"" << node2Name << ".htm\">" << node2Name << "</a>";
		out << "</H3></CENTER>" << endl;
		if (NumberOfMolecules < 2)
		{
			out << "No pathways were found!" << "</body></html>";
		}
		else
		{
		
			out << "<b>Number of molecules:</b> " << NumberOfMolecules << "<br>";
			out << "<b>Number of interactions:</b> " << NumberOfInteractions << "<br>";
			out << "<B>Characteristic Path Length: </B>" << ComputeAvgPathLength() << "<BR>" << endl;
			out << "<B>Clustering coefficient: </B>" << ComputeCC() << "<BR>" << endl;
			out << "<B>Grid coefficient: </B>" << ComputeGC() << "<BR>" << endl;
			out << "<center><a href=\"" << mapNames[i] << ".sig\">Map data in sig format</a></center>" << endl;
			
			out << "<CENTER>" << "<EMBED SRC=\"" << mapNames[i];
			out << ".svg\" width=\"740\" height=\"756\" type=\"image/svg+xml\" /></CENTER>" << endl;
		}	
		FreeNetwork();

		out << "<br>" << endl;
		out << "<center>Copyright &#0169; 2004</center>" << endl;
		out << "</body></html>" << endl;
		out.close();
	}		

	LoadNetwork(OriginalNetworkName);
}
void CTestSVGDlg::OnBnClickedOk()
{
	// TODO: Add your control notification handler code here
	OnOK();
}

int CheckSourceCondition(MOLECULE* tempNode)
{
	int cond = 0;

	if (PathwayGeneratorSetupStruct.sourceCondName1 != "")
	{
		if 	(PathwayGeneratorSetupStruct.sourceCondType1 == "Type")
		{
			if (!strcmp(PathwayGeneratorSetupStruct.sourceCondName1.GetBuffer(), 
				tempNode->moleculeType))
			{
				cond = 1;
			}
		}
		else if 	(PathwayGeneratorSetupStruct.sourceCondType1 == "Name")
		{
			if (!strcmp(PathwayGeneratorSetupStruct.sourceCondName1.GetBuffer(), 
				tempNode->name))
			{
				cond = 1;
			}
		}
		else if 	(PathwayGeneratorSetupStruct.sourceCondType1 == "Location")
		{
			if (!strcmp(PathwayGeneratorSetupStruct.sourceCondName1.GetBuffer(), 
				tempNode->location))
			{
				cond = 1;
			}
		}
	}
	if (PathwayGeneratorSetupStruct.sourceCondName2 != "")
	{
		if 	(PathwayGeneratorSetupStruct.sourceCondType2 == "Type")
		{
			if (!strcmp(PathwayGeneratorSetupStruct.sourceCondName2.GetBuffer(), 
				tempNode->moleculeType))
			{
				cond = 1;
			}
		}
		else if 	(PathwayGeneratorSetupStruct.sourceCondType2 == "Name")
		{
			if (!strcmp(PathwayGeneratorSetupStruct.sourceCondName2.GetBuffer(), 
				tempNode->name))
			{
				cond = 1;
			}
		}
		else if 	(PathwayGeneratorSetupStruct.sourceCondType2 == "Location")
		{
			if (!strcmp(PathwayGeneratorSetupStruct.sourceCondName2.GetBuffer(), 
				tempNode->location))
			{
				cond = 1;
			}
		}
	}
	if (PathwayGeneratorSetupStruct.sourceCondName3 != "")
	{
		if 	(PathwayGeneratorSetupStruct.sourceCondType3 == "Type")
		{
			if (!strcmp(PathwayGeneratorSetupStruct.sourceCondName3.GetBuffer(), 
				tempNode->moleculeType))
			{
				cond = 1;
			}
		}
		else if 	(PathwayGeneratorSetupStruct.sourceCondType3 == "Name")
		{
			if (!strcmp(PathwayGeneratorSetupStruct.sourceCondName3.GetBuffer(), 
				tempNode->name))
			{
				cond = 1;
			}
		}
		else if 	(PathwayGeneratorSetupStruct.sourceCondType3 == "Location")
		{
			if (!strcmp(PathwayGeneratorSetupStruct.sourceCondName3.GetBuffer(), 
				tempNode->location))
			{
				cond = 1;
			}
		}
	}
	if (PathwayGeneratorSetupStruct.sourceCondName4 != "")
	{
		if 	(PathwayGeneratorSetupStruct.sourceCondType4 == "Type")
		{
			if (!strcmp(PathwayGeneratorSetupStruct.sourceCondName4.GetBuffer(), 
				tempNode->moleculeType))
			{
				cond = 1;
			}
		}
		else if 	(PathwayGeneratorSetupStruct.sourceCondType4 == "Name")
		{
			if (!strcmp(PathwayGeneratorSetupStruct.sourceCondName4.GetBuffer(), 
				tempNode->name))
			{
				cond = 1;
			}
		}
		else if 	(PathwayGeneratorSetupStruct.sourceCondType4 == "Location")
		{
			if (!strcmp(PathwayGeneratorSetupStruct.sourceCondName4.GetBuffer(), 
				tempNode->location))
			{
				cond = 1;
			}
		}
	}
	return cond;
}

int CheckTargetCondition(MOLECULE* tempNode)
{
	int cond = 0;

	if (PathwayGeneratorSetupStruct.targetCondName1 != "")
	{
		if 	(PathwayGeneratorSetupStruct.targetCondType1 == "Type")
		{
			if (!strcmp(PathwayGeneratorSetupStruct.targetCondName1.GetBuffer(), 
				tempNode->moleculeType))
			{
				cond = 1;
			}
		}
		else if 	(PathwayGeneratorSetupStruct.targetCondType1 == "Name")
		{
			if (!strcmp(PathwayGeneratorSetupStruct.targetCondName1.GetBuffer(), 
				tempNode->name))
			{
				cond = 1;
			}
		}
		else if 	(PathwayGeneratorSetupStruct.targetCondType1 == "Location")
		{
			if (!strcmp(PathwayGeneratorSetupStruct.targetCondName1.GetBuffer(), 
				tempNode->location))
			{
				cond = 1;
			}
		}
	}
	if (PathwayGeneratorSetupStruct.targetCondName2 != "")
	{
		if 	(PathwayGeneratorSetupStruct.targetCondType2 == "Type")
		{
			if (!strcmp(PathwayGeneratorSetupStruct.targetCondName2.GetBuffer(), 
				tempNode->moleculeType))
			{
				cond = 1;
			}
		}
		else if 	(PathwayGeneratorSetupStruct.targetCondType2 == "Name")
		{
			if (!strcmp(PathwayGeneratorSetupStruct.targetCondName2.GetBuffer(), 
				tempNode->name))
			{
				cond = 1;
			}
		}
		else if 	(PathwayGeneratorSetupStruct.targetCondType2 == "Location")
		{
			if (!strcmp(PathwayGeneratorSetupStruct.targetCondName2.GetBuffer(), 
				tempNode->location))
			{
				cond = 1;
			}
		}
	}
	if (PathwayGeneratorSetupStruct.targetCondName3 != "")
	{
		if 	(PathwayGeneratorSetupStruct.targetCondType3 == "Type")
		{
			if (!strcmp(PathwayGeneratorSetupStruct.targetCondName3.GetBuffer(), 
				tempNode->moleculeType))
			{
				cond = 1;
			}
		}
		else if 	(PathwayGeneratorSetupStruct.targetCondType3 == "Name")
		{
			if (!strcmp(PathwayGeneratorSetupStruct.targetCondName3.GetBuffer(), 
				tempNode->name))
			{
				cond = 1;
			}
		}
		else if 	(PathwayGeneratorSetupStruct.targetCondType3 == "Location")
		{
			if (!strcmp(PathwayGeneratorSetupStruct.targetCondName3.GetBuffer(), 
				tempNode->location))
			{
				cond = 1;
			}
		}
	}
	if (PathwayGeneratorSetupStruct.targetCondName4 != "")
	{
		if 	(PathwayGeneratorSetupStruct.targetCondType4 == "Type")
		{
			if (!strcmp(PathwayGeneratorSetupStruct.targetCondName4.GetBuffer(), 
				tempNode->moleculeType))
			{
				cond = 1;
			}
		}
		else if 	(PathwayGeneratorSetupStruct.targetCondType4 == "Name")
		{
			if (!strcmp(PathwayGeneratorSetupStruct.targetCondName4.GetBuffer(), 
				tempNode->name))
			{
				cond = 1;
			}
		}
		else if 	(PathwayGeneratorSetupStruct.targetCondType4 == "Location")
		{
			if (!strcmp(PathwayGeneratorSetupStruct.targetCondName4.GetBuffer(), 
				tempNode->location))
			{
				cond = 1;
			}
		}
	}
	return cond;
}

void CreatePathwayGeneratorForm(int numberOfMapNames, char* mapNames[])
{
	ofstream out;
	CString formPage;
	CString node1Name;
	CString node2Name;
	CString previousNames[1000];
	int flag;
	int start;
	int i, j;

	formPage = "<html><head><script language=\"JavaScript\">\nfunction redirect()\n{\n    var source_options;\n    var target_options;\n    var source;\n    var target;\n    var url;\n    var flag = 0;\n    \n    source_options = document.form1.source.options;\n    \n    if (source_options.selectedIndex != -1)\n    {\n        source = source_options[source_options.selectedIndex].text;\n    }\n    else\n    {\n	flag = 1;";
	formPage += "\n        alert (\"Source not selected!\");\n    }\n\n    target_options = document.form1.target.options;\n    \n    if (target_options.selectedIndex != -1)\n    {\n        target = target_options[target_options.selectedIndex].text;\n    }\n    else\n    {\n	flag = 1;\n        alert (\"Target not selected!\");\n    }\n\n    url = source + \"_to_\" + target + \".htm\";\n\n    if (flag == 0)\n    {    \n     ";
	formPage += "window.location=url;\n    }\n}\n//-->\n</SCRIPT>\n</HEAD>\n\n\n<body>\n\n\n<form name=\"form1\">\n\n<table>\n<tr><td>\nSelect a source component:<br>\n<select name=\"source\" size=\"8\" multiple>\n";
	
	for (i = 0; i < numberOfMapNames; i++)
	{
		node1Name = mapNames[i];
		node2Name = mapNames[i];

		start = 0;
		node1Name = node2Name.Tokenize("_", start);
		node2Name.Tokenize("_", start);
		node2Name = node2Name.Tokenize("_", start);
		previousNames[i] = node1Name;

		flag = 0;
		for (j = 0; j < i; j++)
		{
			if ( node1Name == previousNames[j])
			{
				flag = 1;
			}
		}

		if (!flag)
		{
			formPage += "<option>";
			formPage += node1Name.GetBuffer();
			formPage += "\n";
		}
	}
		
	
	formPage += "</select>\n</td>\n<td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>\n<td>\nSelect a target component:<br>\n<select name=\"target\" size=\"8\" multiple>\n";
	
	for (i = 0; i < numberOfMapNames; i++)
	{
		node1Name = mapNames[i];
		node2Name = mapNames[i];

		start = 0;
		node1Name = node2Name.Tokenize("_", start);
		node2Name.Tokenize("_", start);
		node2Name = node2Name.Tokenize("_", start);
		previousNames[i] = node2Name;

		flag = 0;
		for (j = 0; j < i; j++)
		{
			if ( node2Name == previousNames[j])
			{
				flag = 1;
			}
		}

		if (!flag)
		{
			formPage += "<option>";
			formPage += node2Name.GetBuffer();
			formPage += "\n";
		}
	}

	formPage += "</select>\n<br>\n</td></tr></table>\n<INPUT type=\"button\" value=\"Draw Pathway\" onclick=\"redirect()\">\n\n</form> \n\n</body>\n</html>\n";

	out.open("form.htm");

	out << formPage.GetBuffer();

	out.close();

}
void CTestSVGDlg::OnBnClickedButtonMotifs()
{
	CDialogMotifsChoices myDialog;

	if (myDialog.DoModal() == IDOK)
	{
		MotifsChoices.m_FBL3 = myDialog.m_checkFBL3;
		MotifsChoices.m_FBL4 = myDialog.m_checkFBL4;

		MotifsChoices.m_FFL3 = myDialog.m_checkFFL3;
		MotifsChoices.m_FFL4 = myDialog.m_checkFFL4;
	
		MotifsChoices.m_Bifans = myDialog.m_checkBifans;
		MotifsChoices.m_Scaffolds = myDialog.m_checkScaffolds;
		
		ShutOffAllButtons();

		if (DirLevel == 0)
		{
			DirLevel = 1;
		}
		else
		{
			chdir("..");	
		}
		mkdir("SNAVI_motifs");
		chdir("SNAVI_motifs");
		// start the thread that computes 
		pThreadFindMotifs = AfxBeginThread(FindMotifsThread,
								GetSafeHwnd(), 
								THREAD_PRIORITY_NORMAL);
	}
	else
	{
		return;
	}
}

UINT FindMotifsThread(LPVOID pParam)
{
	char fileName[100];

	if (MotifsChoices.m_Scaffolds)
	{
		strcpy(MotifsMessage, "Searching for scaffolds... please wait!");
		ProgressCount2 = 0;
		::PostMessage((HWND) pParam, WM_UPDATE_MOTIFS_SEARCH_PROGRESS, 0, 0);
		CountScaffoldCycles(pParam);
		strcpy(fileName, "scaffolds");
		DumpToJpegTopMotif3(fileName);
		CreateWebPageToDisplayTheMotifs3(fileName);
		FreeMotifs();
	}
	if (MotifsChoices.m_Bifans)
	{
		strcpy(MotifsMessage, "Searching for bifans... please wait!");
		ProgressCount2 = 0;
		::PostMessage((HWND) pParam, WM_UPDATE_MOTIFS_SEARCH_PROGRESS, 0, 0);
		CountBifanCycles(pParam);
		strcpy(fileName, "bifans");
		DumpToJpegTopMotif4(fileName);
		CreateWebPageToDisplayTheMotifs4(fileName);
		FreeMotifs();
	}

	if (MotifsChoices.m_FBL3)
	{
		strcpy(MotifsMessage, "Searching for feedback loops of size 3... please wait!");
		ProgressCount2 = 0;
		::PostMessage((HWND) pParam, WM_UPDATE_MOTIFS_SEARCH_PROGRESS, 0, 0);
		CountDirectedCycles(3, pParam);
		strcpy(fileName, "feedback_loops3");
		DumpToJpegTopMotif3(fileName);
		CreateWebPageToDisplayTheMotifs3(fileName);
		FreeMotifs();
	}
	if (MotifsChoices.m_FBL4)
	{
		strcpy(MotifsMessage, "Searching for feedback loops of size 4... please wait!");
		ProgressCount2 = 0;
		::PostMessage((HWND) pParam, WM_UPDATE_MOTIFS_SEARCH_PROGRESS, 0, 0);
		CountDirectedCycles(4, pParam);
		strcpy(fileName, "feedback_loops4");
		DumpToJpegTopMotif4(fileName);
		CreateWebPageToDisplayTheMotifs4(fileName);
		FreeMotifs();
	}

	if (MotifsChoices.m_FFL3)
	{
		strcpy(MotifsMessage, "Searching for feedforward loops of size 3... please wait!");
		ProgressCount2 = 0;
		::PostMessage((HWND) pParam, WM_UPDATE_MOTIFS_SEARCH_PROGRESS, 0, 0);
		CountConvergedCycles(3, pParam);
		strcpy(fileName, "feedforward_loops3");
		DumpToJpegTopMotif3(fileName);
		CreateWebPageToDisplayTheMotifs3(fileName);
		FreeMotifs();
	}
	if (MotifsChoices.m_FFL4)
	{
		strcpy(MotifsMessage, "Searching for feedforward loops of size 4... please wait!");
		ProgressCount2 = 0;
		::PostMessage((HWND) pParam, WM_UPDATE_MOTIFS_SEARCH_PROGRESS, 0, 0);
		CountConvergedCycles(4, pParam);
		strcpy(fileName, "feedforward_loops4");
		DumpToJpegTopMotif4(fileName);
		CreateWebPageToDisplayTheMotifs4(fileName);
		FreeMotifs();
	}

	//craete the home page for the motifs
	ofstream out;

	out.open("motifs.htm");
	out << "<html><body>";
	out << "Found motifs:<br>";
	if (MotifsChoices.m_Scaffolds)
	{
		out << "<a href=\"scaffolds.htm\">Scaffold</a><br>";
	}
	if (MotifsChoices.m_Bifans)
	{
		out << "<a href=\"bifans.htm\">Bifans</a><br>";
	}

	if (MotifsChoices.m_FBL3)
	{
		out << "<a href=\"feedback_loops3.htm\">Feedback loops of size 3</a><br>";
	}
	if (MotifsChoices.m_FBL4)
	{
		out << "<a href=\"feedback_loops4.htm\">Feedback loops of size 4</a><br>";
	}

	if (MotifsChoices.m_FFL3)
	{
		out << "<a href=\"feedforward_loops3.htm\">Feedforward loops of size 3</a><br>";
	}
	if (MotifsChoices.m_FFL4)
	{
		out << "<a href=\"feedforward_loops4.htm\">Feedforward loops of size 4</a><br>";
	}
	out << "</body></html>";

	out.close();

	::PostMessage((HWND) pParam, WM_THREAD_MOTIFS_SEARCH_FINISHED, 0, 0);
	return 0;
}

void StartViewer(char* fileName)
{
	// open the viewer with the main motif search
	CDialogViewer viewerDialog;

	char path[500];
	char fullPath[500];
	CString temp;
	
	if (DirLevel == 0)
	{
		chdir("SNAVI_website");
		DirLevel = 1;
	}

	getcwd(path, 500);
	strcpy(fullPath, "file:///");
	strcat(fullPath, path);
 			 
	strcat(fullPath, "/");
	strcat(fullPath, fileName);	

	temp = fullPath;
	temp.Replace(" ", "%20");
	temp.Replace("\\", "/");
	strcpy(fullPath, temp.GetBuffer());

	
	viewerDialog.homeFile = fileName;

	strcpy(viewerDialog.fileName, fullPath);

	viewerDialog.DoModal();
}

void AddToFBL3Array(char* name1, char* name2, char* name3)
{
	int indexForTranscription;
	int indexForTranslation;
	int indexForVesicles;
	int indexForMotility;
	int indexForChannels;

	GetIndexesFor3NodeMotifs(name1, name2, name3, indexForTranscription,
						indexForTranslation, indexForVesicles,
						indexForMotility, indexForChannels);

	MotifsBetweenCuesAndTranscription[indexForTranscription][0]++;
	MotifsBetweenCuesAndTranslation[indexForTranslation][0]++;
	MotifsBetweenCuesAndVesicles[indexForVesicles][0]++;
	MotifsBetweenCuesAndMotility[indexForMotility][0]++;
	MotifsBetweenCuesAndChannels[indexForChannels][0]++;

	return;
}
void AddToFBL4Array(char* name1, char* name2, char* name3, char* name4)
{
	int indexForTranscription;
	int indexForTranslation;
	int indexForVesicles;
	int indexForMotility;
	int indexForChannels;

	GetIndexesFor4NodeMotifs(name1, name2, name3, name4, indexForTranscription,
						indexForTranslation, indexForVesicles,
						indexForMotility, indexForChannels);

	MotifsBetweenCuesAndTranscription[indexForTranscription][1]++;
	MotifsBetweenCuesAndTranslation[indexForTranslation][1]++;
	MotifsBetweenCuesAndVesicles[indexForVesicles][1]++;
	MotifsBetweenCuesAndMotility[indexForMotility][1]++;
	MotifsBetweenCuesAndChannels[indexForChannels][1]++;
}
void AddToPFBL3Array(char* name1, char* name2, char* name3)
{
	int indexForTranscription;
	int indexForTranslation;
	int indexForVesicles;
	int indexForMotility;
	int indexForChannels;

	GetIndexesFor3NodeMotifs(name1, name2, name3, indexForTranscription,
						indexForTranslation, indexForVesicles,
						indexForMotility, indexForChannels);

	MotifsBetweenCuesAndTranscription[indexForTranscription][2]++;
	MotifsBetweenCuesAndTranslation[indexForTranslation][2]++;
	MotifsBetweenCuesAndVesicles[indexForVesicles][2]++;
	MotifsBetweenCuesAndMotility[indexForMotility][2]++;
	MotifsBetweenCuesAndChannels[indexForChannels][2]++;
}
void AddToPFBL4Array(char* name1, char* name2, char* name3, char* name4)
{
	int indexForTranscription;
	int indexForTranslation;
	int indexForVesicles;
	int indexForMotility;
	int indexForChannels;

	GetIndexesFor4NodeMotifs(name1, name2, name3, name4, indexForTranscription,
						indexForTranslation, indexForVesicles,
						indexForMotility, indexForChannels);

	MotifsBetweenCuesAndTranscription[indexForTranscription][3]++;
	MotifsBetweenCuesAndTranslation[indexForTranslation][3]++;
	MotifsBetweenCuesAndVesicles[indexForVesicles][3]++;
	MotifsBetweenCuesAndMotility[indexForMotility][3]++;
	MotifsBetweenCuesAndChannels[indexForChannels][3]++;
}

void AddToNFBL3Array(char* name1, char* name2, char* name3)
{
	int indexForTranscription;
	int indexForTranslation;
	int indexForVesicles;
	int indexForMotility;
	int indexForChannels;

	GetIndexesFor3NodeMotifs(name1, name2, name3, indexForTranscription,
						indexForTranslation, indexForVesicles,
						indexForMotility, indexForChannels);

	MotifsBetweenCuesAndTranscription[indexForTranscription][4]++;
	MotifsBetweenCuesAndTranslation[indexForTranslation][4]++;
	MotifsBetweenCuesAndVesicles[indexForVesicles][4]++;
	MotifsBetweenCuesAndMotility[indexForMotility][4]++;
	MotifsBetweenCuesAndChannels[indexForChannels][4]++;
}
void AddToNFBL4Array(char* name1, char* name2, char* name3, char* name4)
{
	int indexForTranscription;
	int indexForTranslation;
	int indexForVesicles;
	int indexForMotility;
	int indexForChannels;

	GetIndexesFor4NodeMotifs(name1, name2, name3, name4, indexForTranscription,
						indexForTranslation, indexForVesicles,
						indexForMotility, indexForChannels);

	MotifsBetweenCuesAndTranscription[indexForTranscription][5]++;
	MotifsBetweenCuesAndTranslation[indexForTranslation][5]++;
	MotifsBetweenCuesAndVesicles[indexForVesicles][5]++;
	MotifsBetweenCuesAndMotility[indexForMotility][5]++;
	MotifsBetweenCuesAndChannels[indexForChannels][5]++;	
}

void AddToFFL3Array(char* name1, char* name2, char* name3)
{
	int indexForTranscription;
	int indexForTranslation;
	int indexForVesicles;
	int indexForMotility;
	int indexForChannels;

	GetIndexesFor3NodeMotifs(name1, name2, name3, indexForTranscription,
						indexForTranslation, indexForVesicles,
						indexForMotility, indexForChannels);

	MotifsBetweenCuesAndTranscription[indexForTranscription][6]++;
	MotifsBetweenCuesAndTranslation[indexForTranslation][6]++;
	MotifsBetweenCuesAndVesicles[indexForVesicles][6]++;
	MotifsBetweenCuesAndMotility[indexForMotility][6]++;
	MotifsBetweenCuesAndChannels[indexForChannels][6]++;
}

void AddToFFL4Array(char* name1, char* name2, char* name3, char* name4)
{
	int indexForTranscription;
	int indexForTranslation;
	int indexForVesicles;
	int indexForMotility;
	int indexForChannels;

	GetIndexesFor4NodeMotifs(name1, name2, name3, name4, indexForTranscription,
						indexForTranslation, indexForVesicles,
						indexForMotility, indexForChannels);

	if (indexForChannels == 0)
	{
		int i = 0;
	}
	MotifsBetweenCuesAndTranscription[indexForTranscription][7]++;
	MotifsBetweenCuesAndTranslation[indexForTranslation][7]++;
	MotifsBetweenCuesAndVesicles[indexForVesicles][7]++;
	MotifsBetweenCuesAndMotility[indexForMotility][7]++;
	MotifsBetweenCuesAndChannels[indexForChannels][7]++;

}
void AddToPFFL3Array(char* name1, char* name2, char* name3)
{
	int indexForTranscription;
	int indexForTranslation;
	int indexForVesicles;
	int indexForMotility;
	int indexForChannels;

	GetIndexesFor3NodeMotifs(name1, name2, name3, indexForTranscription,
						indexForTranslation, indexForVesicles,
						indexForMotility, indexForChannels);

	MotifsBetweenCuesAndTranscription[indexForTranscription][8]++;
	MotifsBetweenCuesAndTranslation[indexForTranslation][8]++;
	MotifsBetweenCuesAndVesicles[indexForVesicles][8]++;
	MotifsBetweenCuesAndMotility[indexForMotility][8]++;
	MotifsBetweenCuesAndChannels[indexForChannels][8]++;
}

void AddToPFFL4Array(char* name1, char* name2, char* name3, char* name4)
{
	int indexForTranscription;
	int indexForTranslation;
	int indexForVesicles;
	int indexForMotility;
	int indexForChannels;

	GetIndexesFor4NodeMotifs(name1, name2, name3, name4, indexForTranscription,
						indexForTranslation, indexForVesicles,
						indexForMotility, indexForChannels);

	MotifsBetweenCuesAndTranscription[indexForTranscription][9]++;
	MotifsBetweenCuesAndTranslation[indexForTranslation][9]++;
	MotifsBetweenCuesAndVesicles[indexForVesicles][9]++;
	MotifsBetweenCuesAndMotility[indexForMotility][9]++;
	MotifsBetweenCuesAndChannels[indexForChannels][9]++;
}

void AddToNFFL3Array(char* name1, char* name2, char* name3)
{
	int indexForTranscription;
	int indexForTranslation;
	int indexForVesicles;
	int indexForMotility;
	int indexForChannels;

	GetIndexesFor3NodeMotifs(name1, name2, name3, indexForTranscription,
						indexForTranslation, indexForVesicles,
						indexForMotility, indexForChannels);

	MotifsBetweenCuesAndTranscription[indexForTranscription][10]++;
	MotifsBetweenCuesAndTranslation[indexForTranslation][10]++;
	MotifsBetweenCuesAndVesicles[indexForVesicles][10]++;
	MotifsBetweenCuesAndMotility[indexForMotility][10]++;
	MotifsBetweenCuesAndChannels[indexForChannels][10]++;
}

void AddToNFFL4Array(char* name1, char* name2, char* name3, char* name4)
{
	int indexForTranscription;
	int indexForTranslation;
	int indexForVesicles;
	int indexForMotility;
	int indexForChannels;

	GetIndexesFor4NodeMotifs(name1, name2, name3, name4, indexForTranscription,
						indexForTranslation, indexForVesicles,
						indexForMotility, indexForChannels);

	MotifsBetweenCuesAndTranscription[indexForTranscription][11]++;
	MotifsBetweenCuesAndTranslation[indexForTranslation][11]++;
	MotifsBetweenCuesAndVesicles[indexForVesicles][11]++;
	MotifsBetweenCuesAndMotility[indexForMotility][11]++;
	MotifsBetweenCuesAndChannels[indexForChannels][11]++;
}

void AddToSCAFFOLDArray(char* name1, char* name2, char* name3)
{
	int indexForTranscription;
	int indexForTranslation;
	int indexForVesicles;
	int indexForMotility;
	int indexForChannels;

	GetIndexesFor3NodeMotifs(name1, name2, name3, indexForTranscription,
						indexForTranslation, indexForVesicles,
						indexForMotility, indexForChannels);

	MotifsBetweenCuesAndTranscription[indexForTranscription][12]++;
	MotifsBetweenCuesAndTranslation[indexForTranslation][12]++;
	MotifsBetweenCuesAndVesicles[indexForVesicles][12]++;
	MotifsBetweenCuesAndMotility[indexForMotility][12]++;
	MotifsBetweenCuesAndChannels[indexForChannels][12]++;
}

void AddToBIFANArray(char* name1, char* name2, char* name3, char* name4)
{
	int indexForTranscription;
	int indexForTranslation;
	int indexForVesicles;
	int indexForMotility;
	int indexForChannels;

	GetIndexesFor4NodeMotifs(name1, name2, name3, name4, indexForTranscription,
						indexForTranslation, indexForVesicles,
						indexForMotility, indexForChannels);

	MotifsBetweenCuesAndTranscription[indexForTranscription][13]++;
	MotifsBetweenCuesAndTranslation[indexForTranslation][13]++;
	MotifsBetweenCuesAndVesicles[indexForVesicles][13]++;
	MotifsBetweenCuesAndMotility[indexForMotility][13]++;
	MotifsBetweenCuesAndChannels[indexForChannels][13]++;
}

MOTIF3* AddMotif3(char* name1, char* name2, char* name3, int type, int sign)
{
	MOTIF3* tempNode;
	MOLECULE* tempMol;
	char type1[200];
	char type2[200];
	char type3[200];
	char effect1[200];
	char effect2[200];
	char effect3[200];
	char typeOfInteraction1[200];
	char typeOfInteraction2[200];
	char typeOfInteraction3[200];
	int direction1;
	int direction2;
	int direction3;

	if (These3NamesAlreadyBeenHere(name1, name2, name3))
	{
		return Motif3List;
	}

	
	strcpy(effect1, GetEffectBasedOnNames(name1, name2));
	strcpy(effect2, GetEffectBasedOnNames(name2, name3));
	strcpy(effect3, GetEffectBasedOnNames(name3, name1));

	direction1 = GetDirectionBasedOnNames(name1, name2);
	direction2 = GetDirectionBasedOnNames(name2, name3);
	direction3 = GetDirectionBasedOnNames(name3, name1);


    /* if the list is empty */
    if (!Motif3List)
    {
         /* just store this information */
	    Motif3List = (MOTIF3*) malloc(sizeof(MOTIF3));
		tempMol = GetNodeBasedOnName(name1);
        //strcpy(Motif3List->name1, tempMol->moleculeType);
		strcpy(Motif3List->name1, tempMol->name);
		
		tempMol = GetNodeBasedOnName(name2);
        //strcpy(Motif3List->name2, tempMol->moleculeType);
		strcpy(Motif3List->name2, tempMol->name);

		tempMol = GetNodeBasedOnName(name3);
        //strcpy(Motif3List->name3, tempMol->moleculeType);
		strcpy(Motif3List->name3, tempMol->name);

		strcpy(Motif3List->effect1, GetEffectBasedOnNames(name1, name2));
		strcpy(Motif3List->typeOfInteraction1, GetTypeOfInteractionBasedOnNames(name1, name2));
		Motif3List->direction1 = GetDirectionBasedOnNames(name1, name2);

		strcpy(Motif3List->effect2, GetEffectBasedOnNames(name2, name3));
		strcpy(Motif3List->typeOfInteraction2, GetTypeOfInteractionBasedOnNames(name2, name3));
		Motif3List->direction2 = GetDirectionBasedOnNames(name2, name3);

		strcpy(Motif3List->effect3, GetEffectBasedOnNames(name3, name1));
		strcpy(Motif3List->typeOfInteraction3, GetTypeOfInteractionBasedOnNames(name3, name1));
		Motif3List->direction3 = GetDirectionBasedOnNames(name3, name1);
		
		Motif3List->type = type;
		Motif3List->sign = sign;

	    Motif3List->next = 0;
		if (!FindMotifsInRandomNetwork)
		{
			Motif3List->count = 1;   
		}
		else
		{
			Motif3List->randomCount = 1;
		}
	    NumberOfMotif3++;
	    return Motif3List;	
    }

	tempMol = GetNodeBasedOnName(name1);
    //strcpy(type1, tempMol->moleculeType);
	strcpy(type1, tempMol->name);
		
	tempMol = GetNodeBasedOnName(name2);
    //strcpy(type2, tempMol->moleculeType);
	strcpy(type2, tempMol->name);

	tempMol = GetNodeBasedOnName(name3);
    //strcpy(type3, tempMol->moleculeType);
	strcpy(type3, tempMol->name);

	strcpy(effect1, GetEffectBasedOnNames(name1, name2));
	strcpy(typeOfInteraction1, GetTypeOfInteractionBasedOnNames(name1, name2));
	direction1 = GetDirectionBasedOnNames(name1, name2);

	strcpy(effect2, GetEffectBasedOnNames(name2, name3));
	strcpy(typeOfInteraction2, GetTypeOfInteractionBasedOnNames(name2, name3));
	direction2 = GetDirectionBasedOnNames(name2, name3);

	strcpy(effect3, GetEffectBasedOnNames(name3, name1));
	strcpy(typeOfInteraction3, GetTypeOfInteractionBasedOnNames(name3, name1));
	direction3 = GetDirectionBasedOnNames(name3, name1);

	/* look for a match or loop all the way to the end */
    tempNode = Motif3List;

    /* loop until a match was found or the end */
    while ((tempNode->next != 0) && 
		(!TheSame3TypesEffectsAndDirection(tempNode, type1, type2, type3,
				effect1, effect2, effect3, direction1, direction2, direction3)))
    {
	    tempNode = tempNode->next;
    }

    /* if a match was found add one to the count */
    if (TheSame3TypesEffectsAndDirection(tempNode, type1, type2, type3,
				effect1, effect2, effect3, direction1, direction2, direction3))
	{
		/* check if the link is already there */
		if (!FindMotifsInRandomNetwork)
		{
			tempNode->count++;  
		}
		else
		{
			tempNode->randomCount++;
		}

		return Motif3List;
    }
	else if (tempNode->next)
	{
		AfxMessageBox("Error counting motifs!");
		return Motif3List;
	}

    
	 /* just store this information */
	tempNode->next = (MOTIF3*) malloc(sizeof(MOTIF3));
	tempNode = tempNode->next;
    //strcpy(tempNode->name1, type1);
    //strcpy(tempNode->name2, type2);
    //strcpy(tempNode->name3, type3);
	strcpy(tempNode->name1, name1);
    strcpy(tempNode->name2, name2);
    strcpy(tempNode->name3, name3);
	strcpy(tempNode->effect1, effect1);
    strcpy(tempNode->effect2, effect2);
    strcpy(tempNode->effect3, effect3);
	strcpy(tempNode->typeOfInteraction1, typeOfInteraction1);
    strcpy(tempNode->typeOfInteraction2, typeOfInteraction2);
    strcpy(tempNode->typeOfInteraction3, typeOfInteraction3);
	tempNode->direction1 = direction1;
	tempNode->direction2 = direction2;
	tempNode->direction3 = direction3;
	tempNode->type = type;
	tempNode->sign = sign;
	tempNode->next = 0;
    
	if (!FindMotifsInRandomNetwork)
	{
		tempNode->count = 1;
	}
	else
	{
		tempNode->randomCount = 1;
	}
	
	NumberOfMotif3++;
	
	return Motif3List;	
}

MOTIF4* AddMotif4(char* name1, char* name2, char* name3, char* name4, int type, int sign)
{
	MOTIF4* tempNode;
	MOLECULE* tempMol;
	char type1[200];
	char type2[200];
	char type3[200];
	char type4[200];
	char effect1[200];
	char effect2[200];
	char effect3[200];
	char effect4[200];
	int direction1;
	int direction2;
	int direction3;
	int direction4;
	char typeOfInteraction1[200];
	char typeOfInteraction2[200];
	char typeOfInteraction3[200];
	char typeOfInteraction4[200];

	if ((These4NamesAlreadyBeenHere(name1, name2, name3, name4))) 
		//||
		//(AreThereInBetweenThese4Connections(name1, name2, name3, name4)))
	{
		return Motif4List;
	}

    /* if the list is empty */
    if (!Motif4List)
    {
         /* just store this information */
	    Motif4List = (MOTIF4*) malloc(sizeof(MOTIF4));
		tempMol = GetNodeBasedOnName(name1);
        //strcpy(Motif4List->name1, tempMol->moleculeType);
		strcpy(Motif4List->name1, tempMol->name);

		tempMol = GetNodeBasedOnName(name2);
        //strcpy(Motif4List->name2, tempMol->moleculeType);
		strcpy(Motif4List->name2, tempMol->name);

		tempMol = GetNodeBasedOnName(name3);
        //strcpy(Motif4List->name3, tempMol->moleculeType);
		strcpy(Motif4List->name3, tempMol->name);

		tempMol = GetNodeBasedOnName(name4);
        //strcpy(Motif4List->name4, tempMol->moleculeType);
		strcpy(Motif4List->name4, tempMol->name);

		strcpy(Motif4List->effect1, GetEffectBasedOnNames(name1, name2));
		strcpy(Motif4List->typeOfInteraction1, GetTypeOfInteractionBasedOnNames(name1, name2));
		Motif4List->direction1 = GetDirectionBasedOnNames(name1, name2);

		strcpy(Motif4List->effect2, GetEffectBasedOnNames(name2, name3));
		strcpy(Motif4List->typeOfInteraction2, GetTypeOfInteractionBasedOnNames(name2, name3));
		Motif4List->direction2 = GetDirectionBasedOnNames(name2, name3);

		strcpy(Motif4List->effect3, GetEffectBasedOnNames(name3, name4));
		strcpy(Motif4List->typeOfInteraction3, GetTypeOfInteractionBasedOnNames(name3, name4));
		Motif4List->direction3 = GetDirectionBasedOnNames(name3, name4);

		strcpy(Motif4List->effect4, GetEffectBasedOnNames(name4, name1));
		strcpy(Motif4List->typeOfInteraction4, GetTypeOfInteractionBasedOnNames(name4, name1));
		Motif4List->direction4 = GetDirectionBasedOnNames(name4, name1);

		Motif4List->type = type;
		Motif4List->sign = sign;

	    Motif4List->next = 0;
		if (!FindMotifsInRandomNetwork)
		{
			Motif4List->count = 1;   
		}
		else
		{
			Motif4List->randomCount = 1;
		}  
	    NumberOfMotif4++;
	    return Motif4List;	
    }
    
    
    /* look for a match or loop all the way to the end */
    tempNode = Motif4List;

	tempMol = GetNodeBasedOnName(name1);
    strcpy(type1, tempMol->moleculeType);
	
	tempMol = GetNodeBasedOnName(name2);
    strcpy(type2, tempMol->moleculeType);

	tempMol = GetNodeBasedOnName(name3);
    strcpy(type3, tempMol->moleculeType);

	tempMol = GetNodeBasedOnName(name4);
    strcpy(type4, tempMol->moleculeType);

	strcpy(effect1, GetEffectBasedOnNames(name1, name2));
	strcpy(typeOfInteraction1, GetTypeOfInteractionBasedOnNames(name1, name2));
	direction1 = GetDirectionBasedOnNames(name1, name2);

	strcpy(effect2, GetEffectBasedOnNames(name2, name3));
	strcpy(typeOfInteraction2, GetTypeOfInteractionBasedOnNames(name2, name3));
	direction2 = GetDirectionBasedOnNames(name2, name3);

	strcpy(effect3, GetEffectBasedOnNames(name3, name4));
	strcpy(typeOfInteraction3, GetTypeOfInteractionBasedOnNames(name3, name4));
	direction3 = GetDirectionBasedOnNames(name3, name4);

	strcpy(effect4, GetEffectBasedOnNames(name4, name1));
	strcpy(typeOfInteraction4, GetTypeOfInteractionBasedOnNames(name4, name1));
	direction4 = GetDirectionBasedOnNames(name4, name1);

    /* loop until a match was found or the end */
	while ((tempNode->next != 0) && 
		(!TheSame4Names(tempNode, name1, name2, name3, name4,
		        type1, type2, type3, type4,
				effect1, effect2, effect3, effect4,
				direction1, direction2, direction3, direction4)))
    {
	    tempNode = tempNode->next;
    }

    /* if a match was found add one to the count */
    if (TheSame4Names(tempNode, name1, name2, name3, name4,
		        type1, type2, type3, type4,
				effect1, effect2, effect3, effect4,
				direction1, direction2, direction3, direction4))
	{
		/* check if the link is already there */
		if (!FindMotifsInRandomNetwork)
		{
			tempNode->count++;
		}
		else
		{
			tempNode->randomCount++;
		}
		return Motif4List;
    }
	else if (tempNode->next)
	{
		AfxMessageBox("Error counting motifs!");
		return Motif4List;
	}    
	 /* just store this information */
	tempNode->next = (MOTIF4*) malloc(sizeof(MOTIF4));
	tempNode = tempNode->next;
    
	strcpy(tempNode->name1, name1);
    strcpy(tempNode->name2, name2);
    strcpy(tempNode->name3, name3);
	strcpy(tempNode->name4, name4);
	strcpy(tempNode->effect1, effect1);
    strcpy(tempNode->effect2, effect2);
    strcpy(tempNode->effect3, effect3);
	strcpy(tempNode->effect4, effect4);
	strcpy(tempNode->typeOfInteraction1, typeOfInteraction1);
    strcpy(tempNode->typeOfInteraction2, typeOfInteraction2);
    strcpy(tempNode->typeOfInteraction3, typeOfInteraction3);
	strcpy(tempNode->typeOfInteraction4, typeOfInteraction4);
	tempNode->direction1 = direction1;
	tempNode->direction2 = direction2;
	tempNode->direction3 = direction3;
	tempNode->direction4 = direction4;

	tempNode->type = type;
	tempNode->sign = sign;

	tempNode->next = 0;
	if (!FindMotifsInRandomNetwork)
	{
		tempNode->count = 1;   
	}
	else
	{
		tempNode->randomCount = 1;
	}
	NumberOfMotif4++;
	return Motif4List;	
}

MOTIF5* AddMotif5(char* name1, char* name2, char* name3, char* name4, char* name5)
{
	MOTIF5* tempNode;
	MOLECULE* tempMol;
	char type1[200];
	char type2[200];
	char type3[200];
	char type4[200];
	char type5[200];
	char effect1[200];
	char effect2[200];
	char effect3[200];
	char effect4[200];
	char effect5[200];
	char typeOfInteraction1[200];
	char typeOfInteraction2[200];
	char typeOfInteraction3[200];
	char typeOfInteraction4[200];
	char typeOfInteraction5[200];
	int direction1;
	int direction2;
	int direction3;
	int direction4;
	int direction5;

	if  ((These5NamesAlreadyBeenHere(name1, name2, name3, name4, name5)) ||
		(AreThereInBetweenThese5Connections(name1, name2, name3, name4, name5)))
	{
		return Motif5List;
	}

    /* if the list is empty */
    if (!Motif5List)
    {
         /* just store this information */
	    Motif5List = (MOTIF5*) malloc(sizeof(MOTIF5));
		tempMol = GetNodeBasedOnName(name1);
        strcpy(Motif5List->name1, tempMol->moleculeType);
		
		tempMol = GetNodeBasedOnName(name2);
        strcpy(Motif5List->name2, tempMol->moleculeType);

		tempMol = GetNodeBasedOnName(name3);
        strcpy(Motif5List->name3, tempMol->moleculeType);

		tempMol = GetNodeBasedOnName(name4);
        strcpy(Motif5List->name4, tempMol->moleculeType);
		
		tempMol = GetNodeBasedOnName(name5);
        strcpy(Motif5List->name5, tempMol->moleculeType);

		strcpy(Motif5List->effect1, GetEffectBasedOnNames(name1, name2));
		strcpy(Motif5List->typeOfInteraction1, GetTypeOfInteractionBasedOnNames(name1, name2));
		Motif5List->direction1 = GetDirectionBasedOnNames(name1, name2);

		strcpy(Motif5List->effect2, GetEffectBasedOnNames(name2, name3));
		strcpy(Motif5List->typeOfInteraction2, GetTypeOfInteractionBasedOnNames(name2, name3));
		Motif5List->direction2 = GetDirectionBasedOnNames(name2, name3);

		strcpy(Motif5List->effect3, GetEffectBasedOnNames(name3, name4));
		strcpy(Motif5List->typeOfInteraction3, GetTypeOfInteractionBasedOnNames(name3, name4));
		Motif5List->direction3 = GetDirectionBasedOnNames(name3, name4);

		strcpy(Motif5List->effect4, GetEffectBasedOnNames(name4, name5));
		strcpy(Motif5List->typeOfInteraction4, GetTypeOfInteractionBasedOnNames(name4, name5));
		Motif5List->direction4 = GetDirectionBasedOnNames(name4, name5);

		strcpy(Motif5List->effect5, GetEffectBasedOnNames(name5, name1));
		strcpy(Motif5List->typeOfInteraction5, GetTypeOfInteractionBasedOnNames(name5, name1));
		Motif5List->direction5 = GetDirectionBasedOnNames(name5, name1);

	    Motif5List->next = 0;
		if (!FindMotifsInRandomNetwork)
		{
			Motif5List->count = 1;   
		}
		else
		{
			Motif5List->randomCount = 1;
		}
	    NumberOfMotif5++;
	    return Motif5List;	
    }
    
    
    /* look for a match or loop all the way to the end */
    tempNode = Motif5List;

	tempMol = GetNodeBasedOnName(name1);
    strcpy(type1, tempMol->moleculeType);
		
	tempMol = GetNodeBasedOnName(name2);
    strcpy(type2, tempMol->moleculeType);

	tempMol = GetNodeBasedOnName(name3);
    strcpy(type3, tempMol->moleculeType);

	tempMol = GetNodeBasedOnName(name4);
    strcpy(type4, tempMol->moleculeType);

	tempMol = GetNodeBasedOnName(name5);
    strcpy(type5, tempMol->moleculeType);

	strcpy(effect1, GetEffectBasedOnNames(name1, name2));
	strcpy(typeOfInteraction1, GetTypeOfInteractionBasedOnNames(name1, name2));
	direction1 = GetDirectionBasedOnNames(name1, name2);

	strcpy(effect2, GetEffectBasedOnNames(name2, name3));
	strcpy(typeOfInteraction2, GetTypeOfInteractionBasedOnNames(name2, name3));
	direction2 = GetDirectionBasedOnNames(name2, name3);

	strcpy(effect3, GetEffectBasedOnNames(name3, name4));
	strcpy(typeOfInteraction3, GetTypeOfInteractionBasedOnNames(name3, name4));
	direction3 = GetDirectionBasedOnNames(name3, name4);

	strcpy(effect4, GetEffectBasedOnNames(name4, name5));
	strcpy(typeOfInteraction4, GetTypeOfInteractionBasedOnNames(name4, name5));
	direction4 = GetDirectionBasedOnNames(name4, name5);

	strcpy(effect5, GetEffectBasedOnNames(name5, name1));
	strcpy(typeOfInteraction5, GetTypeOfInteractionBasedOnNames(name5, name1));
	direction5 = GetDirectionBasedOnNames(name5, name1);

    /* loop until a match was found or the end */
    while ((tempNode->next != 0) && (!TheSame5TypesEffectsAndDirection(tempNode, 
				type1, type2, type3, type4, type5,
				effect1, effect2, effect3, effect4, effect5,
				direction1, direction2, direction3, direction4, direction5)))
    {
	    tempNode = tempNode->next;
    }

    /* if a match was found add one to the count */
    if (TheSame5TypesEffectsAndDirection(tempNode, 
				type1, type2, type3, type4, type5,
				effect1, effect2, effect3, effect4, effect5,
				direction1, direction2, direction3, direction4, direction5))
    {
		/* check if the link is already there */
		if (!FindMotifsInRandomNetwork)
		{
			tempNode->count++;   
		}
		else
		{
			tempNode->randomCount++;
		}
		return Motif5List;
    }
	else if (tempNode->next)
	{
		AfxMessageBox("Error counting motifs!");
		return Motif5List;
	}
    
	 /* just store this information */
	tempNode->next = (MOTIF5*) malloc(sizeof(MOTIF5));
	tempNode = tempNode->next;
    strcpy(tempNode->name1, type1);
    strcpy(tempNode->name2, type2);
    strcpy(tempNode->name3, type3);
	strcpy(tempNode->name4, type4);
	strcpy(tempNode->name5, type5);
	strcpy(tempNode->effect1, effect1);
    strcpy(tempNode->effect2, effect2);
    strcpy(tempNode->effect3, effect3);
	strcpy(tempNode->effect4, effect4);
	strcpy(tempNode->effect5, effect5);
	strcpy(tempNode->typeOfInteraction1, typeOfInteraction1);
    strcpy(tempNode->typeOfInteraction2, typeOfInteraction2);
    strcpy(tempNode->typeOfInteraction3, typeOfInteraction3);
	strcpy(tempNode->typeOfInteraction4, typeOfInteraction4);
	strcpy(tempNode->typeOfInteraction5, typeOfInteraction5);
	tempNode->direction1 = direction1;
	tempNode->direction2 = direction2;
	tempNode->direction3 = direction3;
	tempNode->direction4 = direction4;
	tempNode->direction5 = direction5;
	tempNode->next = 0;

	if (!FindMotifsInRandomNetwork)
	{
		tempNode->count = 1;   
	}
	else
	{
		tempNode->randomCount = 1;
	}
	
	NumberOfMotif5++;
	return Motif5List;	
}

int ScaffoldOK(MOLECULE* sourceNode, MOLECULE* targetNode)
{
	INTERACTION* tempNode;

	tempNode = InteractionsList;

	int found = 0;

	while (tempNode)
	{
		if (
			(
			(!strcmp(tempNode->source, sourceNode->name))
			&& 
			(!strcmp(tempNode->target, targetNode->name)) 
			)
			&&
			(!strcmp(tempNode->effect, "0"))
			|| 
			(
			(!strcmp(tempNode->source, targetNode->name))
			&& 
			(!strcmp(tempNode->target, sourceNode->name)) 
		    &&
			(!strcmp(tempNode->effect, "0")) 
			)
			)
		{
			found = 1;
			break;
		}
		tempNode = tempNode->next;
	}

	return found;
}

int OppositeDirectionOK(MOLECULE* sourceNode, MOLECULE* targetNode)
{
	INTERACTION* tempNode;

	tempNode = InteractionsList;

	int found = 0;

	while (tempNode)
	{
		if (
			(
			(!strcmp(tempNode->target, sourceNode->name))
			&& 
			(!strcmp(tempNode->source, targetNode->name)) 
			)
			&&
			(strcmp(tempNode->effect, "0")))
		{
			found = 1;
			break;
		}
		tempNode = tempNode->next;
	}

	return found;
}

int IsItGate(int* listSoFar, int size)
{
	INTERACTION* node;
	MOLECULE* source;
	MOLECULE* target;
	int arm1Positives = 0;
	int arm1Negatives = 0;
	int arm2Positives = 0;
	int arm2Negatives = 0;
	int i;
	
	for (i = 0; i < size - 1; i++)
	{
		source = GetNodeBasedOnNumber(listSoFar[i]);
		target = GetNodeBasedOnNumber(listSoFar[i + 1]);
	
		node = InteractionsList;

		while (node)
		{
			if ((!strcmp(node->source, source->name)) && (!strcmp(node->target, target->name)))
			{
				if (!strcmp(node->effect, "_"))
				{
					arm1Negatives++;
				}	
				else if (!strcmp(node->effect, "+"))
				{
					arm1Positives++;
				}
				break;
			}

			if ((!strcmp(node->target, source->name)) && (!strcmp(node->source, target->name)))
			{
				if (!strcmp(node->effect, "_"))
				{
					arm2Negatives++;
				}	
				else if (!strcmp(node->effect, "+"))
				{
					arm2Positives++;
				}
				break;
			}
			node = node->next;
		}		
	}

	source = GetNodeBasedOnNumber(listSoFar[i]);
	target = GetNodeBasedOnNumber(listSoFar[0]);
	
	node = InteractionsList;

	while (node)
	{
		if ((!strcmp(node->source, source->name)) && (!strcmp(node->target, target->name)))
		{
			if (!strcmp(node->effect, "_"))
			{
				arm1Negatives++;
			}	
			else if (!strcmp(node->effect, "+"))
			{
				arm1Positives++;
			}
			break;
		}
		if ((!strcmp(node->target, source->name)) && (!strcmp(node->source, target->name)))
		{
			if (!strcmp(node->effect, "_"))
			{
				arm2Negatives++;
			}	
			else if (!strcmp(node->effect, "+"))
			{
				arm2Positives++;
			}
			break;
		}
		node = node->next;
	}	

	if ((arm1Negatives % 2) || (arm1Negatives % 2))
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

int IsItSymmetric(int* listSoFar, int size)
{
    INTERACTION* node;
    MOLECULE* source;
    MOLECULE* target;
    int arm1 = 0;
    int arm2 = 0;
    int i;

	//symmetric ffl are only when the size is even
	if (size % 2)
	{
		return 0;
	}

    for (i = 0; i < size - 1; i++)
    {
		source = GetNodeBasedOnNumber(listSoFar[i]);
        target = GetNodeBasedOnNumber(listSoFar[i + 1]);

        node = InteractionsList;

        while (node)
        {
            if ((!strcmp(node->source, source->name)) && (!strcmp(node->target, target->name)))
            {
                arm1++;
                break;
            }

            if ((!strcmp(node->target, source->name)) && (!strcmp(node->source, target->name)))
            {
                arm2++;
                break;
            }
            node = node->next;
        }
    }
        
	source = GetNodeBasedOnNumber(listSoFar[i]);
    target = GetNodeBasedOnNumber(listSoFar[0]);

    node = InteractionsList;

    while (node)
    {
        if ((!strcmp(node->source, source->name)) && (!strcmp(node->target, target->name)))
        {
            arm1++;
            break;
        }
        if ((!strcmp(node->target, source->name)) && (!strcmp(node->source, target->name)))
        {
            arm2++;
            break;
        }
        node = node->next;
	}

	if (arm1 == arm2)
	{
		return 1;
	}

	return 0;
}
void CreateWebPageToDisplayTheMotifs4(char* fileName)
{
	ofstream out;
	MOTIF4* tempNode;
	int count = 0;
	char imageName[200];
	char tempNum[100];
	char tempName[100];

	strcpy(tempName, fileName);
	strcat(tempName, ".htm");

	out.open(tempName);

	out << "<html><body>";
	out << "Total found: " << NumberOfMotif4 << "<br>";
	
	out << "<table>";

	tempNode = Motif4List;

	while (tempNode)
	{

		if (!(count % 4))
		{
			out << "<tr>";
		}

		sprintf(tempNum, "%d", count+1);
		if (strlen(tempNum) == 1)
		{
			sprintf(imageName, "%s_4000%s.jpg\"", fileName, tempNum);
		}
		else if (strlen(tempNum) == 2)
		{
			sprintf(imageName, "%s_400%s.jpg\"", fileName, tempNum);
		}
		else if (strlen(tempNum) == 3)
		{
			sprintf(imageName, "%s_40%s.jpg\"", fileName, tempNum);
		}
		else 
		{
			sprintf(imageName, "%s_4%s.jpg\"", fileName, tempNum);
		}

		out << "<td><IMG SRC=\"" << imageName << "\" >"  << "</td>";

		if (!((count + 1) % 4))
		{
			out << "</tr>" << endl;
		}
		count++;
		tempNode = tempNode->next;
	}

	out << "</table></body></html>";
}

void CreateWebPageToDisplayTheMotifs3(char* fileName)
{
	ofstream out;
	MOTIF3* tempNode;
	int count = 0;
	char imageName[200];
	char tempNum[100];
	char tempName[100];

	strcpy(tempName, fileName);
	strcat(tempName, ".htm");

	out.open(tempName);

	out << "<html><body>";
	out << "Total found: " << NumberOfMotif3 << "<br>";
	
	out << "<table>";


	tempNode = Motif3List;

	while (tempNode)
	{

		if (!((count) % 4))
		{
			out << "<tr>";
		}

		sprintf(tempNum, "%d", count+1);
		if (strlen(tempNum) == 1)
		{
			sprintf(imageName, "%s_3000%s.jpg\"", fileName, tempNum);
		}
		else if (strlen(tempNum) == 2)
		{
			sprintf(imageName, "%s_300%s.jpg\"", fileName, tempNum);
		}
		else if (strlen(tempNum) == 3)
		{
			sprintf(imageName, "%s_30%s.jpg\"", fileName, tempNum);
		}
		else 
		{
			sprintf(imageName, "%s_3%s.jpg\"", fileName, tempNum);
		}

		out << "<td><IMG SRC=\"" << imageName << "\">"  << "</td>";

		if (!((count + 1) % 4))
		{
			out << "</tr>" << endl;
		}
		count++;
		tempNode = tempNode->next;
	}

	out << "</table></body></html>";
}

void GetIndexesFor3NodeMotifs(char* name1, char* name2, char* name3, 
							  int& indexForTranscription,
							  int& indexForTranslation,
							  int& indexForVesicles,
							  int& indexForMotility,
							  int& indexForChannels)
{
	MOLECULE* tempNode1;
	MOLECULE* tempNode2;
	MOLECULE* tempNode3;
	double avgToTranslation;
	double avgToTranscription;
	double avgToMotility;
	double avgToChannels;
	double avgToVesicles;

	tempNode1 = GetNodeBasedOnName(name1);
	tempNode2 = GetNodeBasedOnName(name2);
	tempNode3 = GetNodeBasedOnName(name3);

	avgToTranslation = ((tempNode1->distanceToTranslation / 
		(tempNode1->distanceToCues + tempNode1->distanceToTranslation)) +
		(tempNode2->distanceToTranslation / 
		(tempNode2->distanceToCues + tempNode2->distanceToTranslation)) +
		(tempNode3->distanceToTranslation / 
		(tempNode3->distanceToCues + tempNode3->distanceToTranslation))) / 3;

	avgToTranscription = ((tempNode1->distanceToTranscription / 
		(tempNode1->distanceToCues + tempNode1->distanceToTranscription)) +
		(tempNode2->distanceToTranscription / 
		(tempNode2->distanceToCues + tempNode2->distanceToTranscription)) +
		(tempNode3->distanceToTranscription / 
		(tempNode3->distanceToCues + tempNode3->distanceToTranscription))) / 3;

	avgToMotility = ((tempNode1->distanceToMotility / 
		(tempNode1->distanceToCues + tempNode1->distanceToMotility)) +
		(tempNode2->distanceToMotility / 
		(tempNode2->distanceToCues + tempNode2->distanceToMotility)) +
		(tempNode3->distanceToMotility / 
		(tempNode3->distanceToCues + tempNode3->distanceToMotility))) / 3;

	avgToChannels = ((tempNode1->distanceToChannels / 
		(tempNode1->distanceToCues + tempNode1->distanceToChannels)) +
		(tempNode2->distanceToChannels / 
		(tempNode2->distanceToCues + tempNode2->distanceToChannels)) +
		(tempNode3->distanceToChannels / 
		(tempNode3->distanceToCues + tempNode3->distanceToChannels))) / 3;

	avgToVesicles = ((tempNode1->distanceToVesicles / 
		(tempNode1->distanceToCues + tempNode1->distanceToVesicles)) +
		(tempNode2->distanceToVesicles / 
		(tempNode2->distanceToCues + tempNode2->distanceToVesicles)) +
		(tempNode3->distanceToVesicles / 
		(tempNode3->distanceToCues + tempNode3->distanceToVesicles))) / 3;

	indexForTranscription = (int) (avgToTranscription * NUMBER_OF_ENTRIES_IN_CUES_TO_MOTIFS);
	indexForTranslation = (int) (avgToTranslation * NUMBER_OF_ENTRIES_IN_CUES_TO_MOTIFS);
	indexForVesicles = (int) (avgToVesicles * NUMBER_OF_ENTRIES_IN_CUES_TO_MOTIFS);
	indexForMotility = (int) (avgToMotility * NUMBER_OF_ENTRIES_IN_CUES_TO_MOTIFS);
	indexForChannels = (int) (avgToChannels * NUMBER_OF_ENTRIES_IN_CUES_TO_MOTIFS);
}

void GetIndexesFor4NodeMotifs(char* name1, char* name2, char* name3, char* name4,
							  int& indexForTranscription,
							  int& indexForTranslation,
							  int& indexForVesicles,
							  int& indexForMotility,
							  int& indexForChannels)
{
	MOLECULE* tempNode1;
	MOLECULE* tempNode2;
	MOLECULE* tempNode3;
	MOLECULE* tempNode4;
	double avgToTranslation;
	double avgToTranscription;
	double avgToMotility;
	double avgToChannels;
	double avgToVesicles;

	tempNode1 = GetNodeBasedOnName(name1);
	tempNode2 = GetNodeBasedOnName(name2);
	tempNode3 = GetNodeBasedOnName(name3);
	tempNode4 = GetNodeBasedOnName(name4);

	avgToTranslation = ((tempNode1->distanceToTranslation / 
		(tempNode1->distanceToCues + tempNode1->distanceToTranslation)) +
		(tempNode2->distanceToTranslation / 
		(tempNode2->distanceToCues + tempNode2->distanceToTranslation)) +
		(tempNode3->distanceToTranslation / 
		(tempNode3->distanceToCues + tempNode3->distanceToTranslation)) +
		(tempNode4->distanceToTranslation / 
		(tempNode4->distanceToCues + tempNode4->distanceToTranslation))) / 4;

	avgToTranscription = ((tempNode1->distanceToTranscription / 
		(tempNode1->distanceToCues + tempNode1->distanceToTranscription)) +
		(tempNode2->distanceToTranscription / 
		(tempNode2->distanceToCues + tempNode2->distanceToTranscription)) +
		(tempNode3->distanceToTranscription / 
		(tempNode3->distanceToCues + tempNode3->distanceToTranscription)) +
		(tempNode4->distanceToTranscription / 
		(tempNode4->distanceToCues + tempNode4->distanceToTranscription))) / 4;

	avgToMotility = ((tempNode1->distanceToMotility / 
		(tempNode1->distanceToCues + tempNode1->distanceToMotility)) +
		(tempNode2->distanceToMotility / 
		(tempNode2->distanceToCues + tempNode2->distanceToMotility)) +
		(tempNode3->distanceToMotility / 
		(tempNode3->distanceToCues + tempNode3->distanceToMotility)) +
		(tempNode4->distanceToMotility / 
		(tempNode4->distanceToCues + tempNode4->distanceToMotility))) / 4;

	avgToChannels = ((tempNode1->distanceToChannels / 
		(tempNode1->distanceToCues + tempNode1->distanceToChannels)) +
		(tempNode2->distanceToChannels / 
		(tempNode2->distanceToCues + tempNode2->distanceToChannels)) +
		(tempNode3->distanceToChannels / 
		(tempNode3->distanceToCues + tempNode3->distanceToChannels)) +
		(tempNode4->distanceToChannels / 
		(tempNode4->distanceToCues + tempNode4->distanceToChannels))) / 4;

	avgToVesicles = ((tempNode1->distanceToVesicles / 
		(tempNode1->distanceToCues + tempNode1->distanceToVesicles)) +
		(tempNode2->distanceToVesicles / 
		(tempNode2->distanceToCues + tempNode2->distanceToVesicles)) +
		(tempNode3->distanceToVesicles / 
		(tempNode3->distanceToCues + tempNode3->distanceToVesicles)) +
		(tempNode4->distanceToVesicles / 
		(tempNode4->distanceToCues + tempNode4->distanceToVesicles))) / 4;

	indexForTranscription = (int) (avgToTranscription * NUMBER_OF_ENTRIES_IN_CUES_TO_MOTIFS);
	indexForTranslation = (int) (avgToTranslation * NUMBER_OF_ENTRIES_IN_CUES_TO_MOTIFS);
	indexForVesicles = (int) (avgToVesicles * NUMBER_OF_ENTRIES_IN_CUES_TO_MOTIFS);
	indexForMotility = (int) (avgToMotility * NUMBER_OF_ENTRIES_IN_CUES_TO_MOTIFS);
	indexForChannels = (int) (avgToChannels * NUMBER_OF_ENTRIES_IN_CUES_TO_MOTIFS);
}

char* GetEffectBasedOnNames(char* name1, char* name2)
{
    INTERACTION* tempInt;

	tempInt = InteractionsList;

	while (tempInt)
	{
		if (((!strcmp(tempInt->source, name1)) && (!strcmp(tempInt->target, name2)))
		|| ((!strcmp(tempInt->source, name2)) && (!strcmp(tempInt->target, name1))))
		{
			return tempInt->effect;
		}
		tempInt = tempInt->next;
	}
	return 0;
}

int GetDirectionBasedOnNames(char* name1, char* name2)
{
	INTERACTION* tempInt;

	tempInt = InteractionsList;

	while (tempInt)
	{
		if (((!strcmp(tempInt->source, name1)) && (!strcmp(tempInt->target, name2)))
		|| ((!strcmp(tempInt->source, name2)) && (!strcmp(tempInt->target, name1))))
		{
			if (!strcmp(tempInt->effect, "0"))
			{
				return 0;
			}
			else if ((!strcmp(tempInt->source, name1)) && (!strcmp(tempInt->target, name2)))
			{
				return 1;
			}
			else
			{
				return -1;
			}
		}
		tempInt = tempInt->next;
	}
	return 0;
}

char* GetTypeOfInteractionBasedOnNames(char* name1, char* name2)
{
    INTERACTION* tempInt;

	tempInt = InteractionsList;

	while (tempInt)
	{
		if (((!strcmp(tempInt->source, name1)) && (!strcmp(tempInt->target, name2)))
		|| ((!strcmp(tempInt->source, name2)) && (!strcmp(tempInt->target, name1))))
		{
			return tempInt->typeOfInteraction;
		}
		tempInt = tempInt->next;
	}
	return 0;
}

int TheSame3TypesEffectsAndDirection(MOTIF3* tempNode, char* type1, char* type2, char* type3,
				char* effect1, char* effect2, char* effect3, 
				int &direction1, int &direction2, int &direction3)
{
	char temp[100];
	int tempInt;

	if ((
		  ((!strcmp("Kinase", type1)) && 
		  (!strcmp("TF", type2)) && 
		  (!strcmp("TF", type3))) ||
		  ((!strcmp("Kinase", type3)) && 
		  (!strcmp("TF", type1)) && 
		  (!strcmp("TF", type2))) ||
		  ((!strcmp("Kinase", type2)) && 
		  (!strcmp("TF", type3)) && 
		  (!strcmp("TF", type1))) ||
		  ((!strcmp("Kinase", type3)) && 
		  (!strcmp("TF", type2)) && 
		  (!strcmp("TF", type1))) ||
		  ((!strcmp("Kinase", type1)) && 
		  (!strcmp("TF", type3)) && 
		  (!strcmp("TF", type2))) ||
		  ((!strcmp("Kinase", type2)) && 
		  (!strcmp("TF", type1)) && 
		  (!strcmp("TF", type3)))
		  ) &&
	      (
		  ((!strcmp(tempNode->name1, type1)) && 
		  (!strcmp(tempNode->name2, type2)) && 
		  (!strcmp(tempNode->name3, type3))) ||
		  ((!strcmp(tempNode->name1, type3)) && 
		  (!strcmp(tempNode->name2, type1)) && 
		  (!strcmp(tempNode->name3, type2))) ||
		  ((!strcmp(tempNode->name1, type2)) && 
		  (!strcmp(tempNode->name2, type3)) && 
		  (!strcmp(tempNode->name3, type1))) ||
		  ((!strcmp(tempNode->name1, type3)) && 
		  (!strcmp(tempNode->name2, type2)) && 
		  (!strcmp(tempNode->name3, type1))) ||
		  ((!strcmp(tempNode->name1, type1)) && 
		  (!strcmp(tempNode->name2, type3)) && 
		  (!strcmp(tempNode->name3, type2))) ||
		  ((!strcmp(tempNode->name1, type2)) && 
		  (!strcmp(tempNode->name2, type1)) && 
		  (!strcmp(tempNode->name3, type3))))
	   )
	{
		tempInt = 1;
	}

	if (
		 ((!strcmp(tempNode->name1, type1)) && 
		  (!strcmp(tempNode->name2, type2)) && 
		  (!strcmp(tempNode->name3, type3)) &&
		  (!strcmp(tempNode->effect1, effect1)) && 
		  (!strcmp(tempNode->effect2, effect2)) && 
		  (!strcmp(tempNode->effect3, effect3)) &&
		  (direction1 == tempNode->direction1) && 
		  (direction2 == tempNode->direction2) && 
		  (direction3 == tempNode->direction3)))
	{
		return 1;
	}

	if   ((!strcmp(tempNode->name1, type2)) && 
		  (!strcmp(tempNode->name2, type3)) && 
		  (!strcmp(tempNode->name3, type1)) &&
		  (!strcmp(tempNode->effect1, effect2)) && 
		  (!strcmp(tempNode->effect2, effect3)) && 
		  (!strcmp(tempNode->effect3, effect1)))
	{
		RotateRight3(type1, type2, type3, effect1, effect2, effect3, 
				direction1, direction2, direction3);
	}
	else if ((!strcmp(tempNode->name1, type3)) && 
		  (!strcmp(tempNode->name2, type1)) && 
		  (!strcmp(tempNode->name3, type2)) &&
		  (!strcmp(tempNode->effect1, effect3)) && 
		  (!strcmp(tempNode->effect2, effect1)) && 
		  (!strcmp(tempNode->effect3, effect2)))
	{
		RotateRight3(type1, type2, type3, effect1, effect2, effect3, 
				direction1, direction2, direction3);
		RotateRight3(type1, type2, type3, effect1, effect2, effect3, 
				direction1, direction2, direction3);
	}
	else if ((!strcmp(tempNode->name1, type1)) && 
		  (!strcmp(tempNode->name2, type3)) && 
		  (!strcmp(tempNode->name3, type2)) &&
		  (strcmp(type2, type3)) &&
		  (!strcmp(tempNode->effect1, effect1)) && 
		  (!strcmp(tempNode->effect2, effect3)) && 
		  (!strcmp(tempNode->effect3, effect2)))
	{
		RotateRight3(type1, type2, type3, effect1, effect2, effect3, 
				direction1, direction2, direction3);
		RotateRight3(type1, type2, type3, effect1, effect2, effect3, 
				direction1, direction2, direction3);
		FlipToInverse3(type1, type2, type3, effect1, effect2, effect3, 
				direction1, direction2, direction3);
	}
	else if ((!strcmp(tempNode->name1, type2)) && 
		  (!strcmp(tempNode->name2, type1)) && 
		  (!strcmp(tempNode->name3, type3)) &&
		  (strcmp(type1, type2)) &&
		  (!strcmp(tempNode->effect1, effect2)) && 
		  (!strcmp(tempNode->effect2, effect1)) && 
		  (!strcmp(tempNode->effect3, effect3)))
	{
		
		RotateRight3(type1, type2, type3, effect1, effect2, effect3, 
				direction1, direction2, direction3);
		FlipToInverse3(type1, type2, type3, effect1, effect2, effect3, 
				direction1, direction2, direction3);
	}
	else if ((!strcmp(tempNode->name1, type3)) && 
		  (!strcmp(tempNode->name2, type2)) && 
		  (!strcmp(tempNode->name3, type1)) &&
		  (strcmp(type1, type3)) &&
		  (!strcmp(tempNode->effect1, effect3)) && 
		  (!strcmp(tempNode->effect2, effect2)) && 
		  (!strcmp(tempNode->effect3, effect1)))
	{
		FlipToInverse3(type1, type2, type3, effect1, effect2, effect3, 
				direction1, direction2, direction3);
	}

	if (
		 ((!strcmp(tempNode->name1, type1)) && 
		  (!strcmp(tempNode->name2, type2)) && 
		  (!strcmp(tempNode->name3, type3)) &&
		  (!strcmp(tempNode->effect1, effect1)) && 
		  (!strcmp(tempNode->effect2, effect2)) && 
		  (!strcmp(tempNode->effect3, effect3)) &&
		  (direction1 == tempNode->direction1) && 
		  (direction2 == tempNode->direction2) && 
		  (direction3 == tempNode->direction3)))
	{
		return 1;
	}
	else
	{
		if ((!strcmp(type1, type2)) || (!strcmp(type2, type3)) ||
			(!strcmp(type1, type3)))
		{
			//check for symmetry and flip
			if ((!strcmp(type2, type3)) &&
			//(!strcmp(effect1, effect3)) &&
			((direction1 + direction3) == 0))
			{
				if (direction2 == 1)
				{
					direction2 = -1;
				}
				else if (direction2 == -1)
				{
					direction2 = 1;
				}
				strcpy(temp, effect1);
				strcpy(effect1, effect3);
				strcpy(effect3, temp);
			}
			else if ((!strcmp(type1, type2)) &&
				//(!strcmp(effect2, effect3)) &&
				((direction2 + direction3) == 0))
			{
				if (direction1 == 1)
				{
					direction1 = -1;
				}
				else if (direction2 == -1)
				{
					direction1 = 1;
				}
				strcpy(temp, effect2);
				strcpy(effect2, effect3);
				strcpy(effect3, temp);
			}
		
			else if ((!strcmp(type3, type1)) &&
				//(!strcmp(effect2, effect1)) &&
				((direction2 + direction1) == 0))
			{
				if (direction3 == 1)
				{
					direction3 = -1;
				}
				else if (direction2 == -1)
				{
					direction3 = 1;
				}
				strcpy(temp, effect1);
				strcpy(effect1, effect2);
				strcpy(effect2, temp);
			}
		}

		if (
		 ((!strcmp(tempNode->name1, type1)) && 
		  (!strcmp(tempNode->name2, type2)) && 
		  (!strcmp(tempNode->name3, type3)) &&
		  (!strcmp(tempNode->effect1, effect1)) && 
		  (!strcmp(tempNode->effect2, effect2)) && 
		  (!strcmp(tempNode->effect3, effect3)) &&
		  (direction1 == tempNode->direction1) && 
		  (direction2 == tempNode->direction2) && 
		  (direction3 == tempNode->direction3)))
		{
			return 1;
		}

		if ((!strcmp(tempNode->name1, type2)) && 
		  (!strcmp(tempNode->name2, type3)) && 
		  (!strcmp(tempNode->name3, type1)) &&
		  (!strcmp(tempNode->effect1, effect2)) && 
		  (!strcmp(tempNode->effect2, effect3)) && 
		  (!strcmp(tempNode->effect3, effect1)))
		{
			RotateRight3(type1, type2, type3, effect1, effect2, effect3, 
				direction1, direction2, direction3);
		}
		else if ((!strcmp(tempNode->name1, type3)) && 
		  (!strcmp(tempNode->name2, type1)) && 
		  (!strcmp(tempNode->name3, type2)) &&
		  (!strcmp(tempNode->effect1, effect3)) && 
		  (!strcmp(tempNode->effect2, effect1)) && 
		  (!strcmp(tempNode->effect3, effect2)))
		{
			RotateRight3(type1, type2, type3, effect1, effect2, effect3, 
				direction1, direction2, direction3);
			RotateRight3(type1, type2, type3, effect1, effect2, effect3, 
				direction1, direction2, direction3);
		}
		else if ((!strcmp(tempNode->name1, type1)) && 
		  (!strcmp(tempNode->name2, type3)) && 
		  (!strcmp(tempNode->name3, type2)) &&
		  (strcmp(type3, type2)) &&
		  (!strcmp(tempNode->effect1, effect1)) && 
		  (!strcmp(tempNode->effect2, effect3)) && 
		  (!strcmp(tempNode->effect3, effect2)))
		{	
			RotateRight3(type1, type2, type3, effect1, effect2, effect3, 
					direction1, direction2, direction3);
			RotateRight3(type1, type2, type3, effect1, effect2, effect3, 
					direction1, direction2, direction3);
			FlipToInverse3(type1, type2, type3, effect1, effect2, effect3, 
					direction1, direction2, direction3);
		}
		else if ((!strcmp(tempNode->name1, type2)) && 
		  (!strcmp(tempNode->name2, type1)) && 
		  (!strcmp(tempNode->name3, type3)) &&
		  (strcmp(type1, type2)) &&
		  (!strcmp(tempNode->effect1, effect2)) && 
		  (!strcmp(tempNode->effect2, effect1)) && 
		  (!strcmp(tempNode->effect3, effect3)))
		{
			RotateRight3(type1, type2, type3, effect1, effect2, effect3, 
					direction1, direction2, direction3);
			FlipToInverse3(type1, type2, type3, effect1, effect2, effect3, 
					direction1, direction2, direction3);
		}
		else if ((!strcmp(tempNode->name1, type3)) && 
		  (!strcmp(tempNode->name2, type2)) && 
		  (!strcmp(tempNode->name3, type1)) &&
		  (strcmp(type1, type3)) &&
		  (!strcmp(tempNode->effect1, effect3)) && 
		  (!strcmp(tempNode->effect2, effect2)) && 
		  (!strcmp(tempNode->effect3, effect1)))
		{
			FlipToInverse3(type1, type2, type3, effect1, effect2, effect3, 
					direction1, direction2, direction3);
		}

		if (
		 ((!strcmp(tempNode->name1, type1)) && 
		  (!strcmp(tempNode->name2, type2)) && 
		  (!strcmp(tempNode->name3, type3)) &&
		  (!strcmp(tempNode->effect1, effect1)) && 
		  (!strcmp(tempNode->effect2, effect2)) && 
		  (!strcmp(tempNode->effect3, effect3)) &&
		  (direction1 == tempNode->direction1) && 
		  (direction2 == tempNode->direction2) && 
		  (direction3 == tempNode->direction3)))
		{
			return 1;
		}
		else
		{
			return 0;
		}
	}
}

void RotateRight3(char* type1, char* type2, char* type3, char* effect1, char* effect2, char* effect3, 
				int &direction1, int &direction2, int &direction3)
{
	char tempStr[100];
	int tempInt;
	
	strcpy(tempStr, type1);
	strcpy(type1, type3);
	strcpy(type3, type2);
	strcpy(type2, tempStr);

	strcpy(tempStr, effect1);
	strcpy(effect1, effect3);
	strcpy(effect3, effect2);
	strcpy(effect2, tempStr);

	tempInt = direction1;
	direction1 = direction3;
	direction3 = direction2;
	direction2 = tempInt;

	return;
}
void FlipToInverse3(char* type1, char* type2, char* type3, char* effect1, char* effect2, char* effect3, 
				int &direction1, int &direction2, int &direction3)
{
	char tempStr[100];
	int tempInt;
	
	strcpy(tempStr, type1);
	strcpy(type1, type3);
	strcpy(type3, tempStr);

	strcpy(tempStr, effect1);
	strcpy(effect1, effect3);
	strcpy(effect3, tempStr);

	tempInt = direction1;
	direction1 = direction3;
	direction3 = tempInt;

	if (direction1 == 1)
	{
		direction1 = -1;
	}
	else if (direction1 == -1)
	{
		direction1 = 1;
	}

	if (direction2 == 1)
	{
		direction2 = -1;
	}
	else if (direction2 == -1)
	{
		direction2 = 1;
	}

	if (direction3 == 1)
	{
		direction3 = -1;
	}
	else if (direction3 == -1)
	{
		direction3 = 1;
	}
}

void RotateRight4(char* type1, char* type2, char* type3, char* type4, 
				  char* effect1, char* effect2, char* effect3, char* effect4,
				  int &direction1, int &direction2, int &direction3, int &direction4)
{
	char tempStr[100];
	int tempInt;
	
	strcpy(tempStr, type1);
	strcpy(type1, type4);
	strcpy(type4, type3);
	strcpy(type3, type2);
	strcpy(type2, tempStr);

	strcpy(tempStr, effect1);
	strcpy(effect1, effect4);
	strcpy(effect4, effect3);
	strcpy(effect3, effect2);
	strcpy(effect2, tempStr);

	tempInt = direction1;
	direction1 = direction4;
	direction4 = direction3;
	direction3 = direction2;
	direction2 = tempInt;

	return;
}
void FlipToInverse4(char* type1, char* type2, char* type3, char* type4, 
					char* effect1, char* effect2, char* effect3, char* effect4,
					int &direction1, int &direction2, int &direction3, int &direction4)
{
	char tempStr[100];
	int tempInt;
	
	strcpy(tempStr, type1);
	strcpy(type1, type4);
	strcpy(type4, tempStr);
	strcpy(tempStr, type2);
	strcpy(type2, type3);
	strcpy(type3, tempStr);

	strcpy(tempStr, effect1);
	strcpy(effect1, effect4);
	strcpy(effect4, tempStr);
	strcpy(tempStr, effect2);
	strcpy(effect2, effect3);
	strcpy(effect3, tempStr);

	tempInt = direction1;
	direction1 = direction4;
	direction4 = tempInt;
	tempInt = direction2;
	direction2 = direction3;
	direction3 = tempInt;

	if (direction1 == 1)
	{
		direction1 = -1;
	}
	else if (direction1 == -1)
	{
		direction1 = 1;
	}

	if (direction2 == 1)
	{
		direction2 = -1;
	}
	else if (direction2 == -1)
	{
		direction2 = 1;
	}

	if (direction3 == 1)
	{
		direction3 = -1;
	}
	else if (direction3 == -1)
	{
		direction3 = 1;
	}

	if (direction4 == 1)
	{
		direction4 = -1;
	}
	else if (direction4 == -1)
	{
		direction4 = 1;
	}
}

void RotateRight5(char* type1, char* type2, char* type3, char* type4, char* type5,
				  char* effect1, char* effect2, char* effect3, char* effect4, char* effect5, 
				  int &direction1, int &direction2, int &direction3, int &direction4, int &direction5)
{
	char tempStr[100];
	int tempInt;
	
	strcpy(tempStr, type1);
	strcpy(type1, type5);
	strcpy(type5, type4);
	strcpy(type4, type3);
	strcpy(type3, type2);
	strcpy(type2, tempStr);

	strcpy(tempStr, effect1);
	strcpy(effect1, effect5);
	strcpy(effect5, effect4);
	strcpy(effect4, effect3);
	strcpy(effect3, effect2);
	strcpy(effect2, tempStr);

	tempInt = direction1;
	direction1 = direction5;
	direction5 = direction4;
	direction4 = direction3;
	direction3 = direction2;
	direction2 = tempInt;

	return;
}
void FlipToInverse5(char* type1, char* type2, char* type3, char* type4, char* type5,
					char* effect1, char* effect2, char* effect3, char* effect4, char* effect5,
					int &direction1, int &direction2, int &direction3, int &direction4, int &direction5)
{
	char tempStr[100];
	int tempInt;
	
	strcpy(tempStr, type1);
	strcpy(type1, type5);
	strcpy(type5, tempStr);
	strcpy(tempStr, type2);
	strcpy(type2, type4);
	strcpy(type4, tempStr);

	strcpy(tempStr, effect1);
	strcpy(effect1, effect5);
	strcpy(effect5, tempStr);
	strcpy(tempStr, effect2);
	strcpy(effect2, effect4);
	strcpy(effect4, tempStr);

	tempInt = direction1;
	direction1 = direction5;
	direction5 = tempInt;
	tempInt = direction2;
	direction2 = direction4;
	direction4 = tempInt;

	if (direction1 == 1)
	{
		direction1 = -1;
	}
	else if (direction1 == -1)
	{
		direction1 = 1;
	}

	if (direction2 == 1)
	{
		direction2 = -1;
	}
	else if (direction2 == -1)
	{
		direction2 = 1;
	}

	if (direction3 == 1)
	{
		direction3 = -1;
	}
	else if (direction3 == -1)
	{
		direction3 = 1;
	}

	if (direction4 == 1)
	{
		direction4 = -1;
	}
	else if (direction4 == -1)
	{
		direction4 = 1;
	}

	if (direction5 == 1)
	{
		direction5 = -1;
	}
	else if (direction5 == -1)
	{
		direction5 = 1;
	}
}

int TheSame4TypesEffectsAndDirection(MOTIF4* tempNode, 
				char* type1, char* type2, char* type3, char* type4,
				char* effect1, char* effect2, char* effect3, char* effect4,
				int& direction1, int& direction2, int& direction3, int& direction4)
{
	int tempInt;
	char temp[100];
	if ((
		  ((!strcmp("Receptor", type1)) && 
		  (!strcmp("Gprotein", type2)) && 
		  (!strcmp("Cyclase", type3)) &&
		  (!strcmp("Gprotein", type4))) ||
		  ((!strcmp("Receptor", type2)) && 
		  (!strcmp("Gprotein", type3)) && 
		  (!strcmp("Cyclase", type4)) &&
		  (!strcmp("Gprotein", type1))) ||
		  ((!strcmp("Receptor", type3)) && 
		  (!strcmp("Gprotein", type4)) && 
		  (!strcmp("Cyclase", type1)) &&
		  (!strcmp("Gprotein", type2))) ||
		  ((!strcmp("Receptor", type2)) && 
		  (!strcmp("Gprotein", type3)) && 
		  (!strcmp("Cyclase", type4)) &&
		  (!strcmp("Gprotein", type1))) ||
		  ((!strcmp("Receptor", type4)) && 
		  (!strcmp("Gprotein", type3)) && 
		  (!strcmp("Cyclase", type2)) &&
		  (!strcmp("Gprotein", type1))) ||
		  ((!strcmp("Receptor", type3)) && 
		  (!strcmp("Gprotein", type2)) && 
		  (!strcmp("Cyclase", type1)) &&
		  (!strcmp("Gprotein", type4))) ||
		  ((!strcmp("Receptor", type2)) && 
		  (!strcmp("Gprotein", type1)) && 
		  (!strcmp("Cyclase", type4)) &&
		  (!strcmp("Gprotein", type3))) ||
		  ((!strcmp("Receptor", type1)) && 
		  (!strcmp("Gprotein", type4)) && 
		  (!strcmp("Cyclase", type3)) &&
		  (!strcmp("Gprotein", type2)))
	   ) &&
	   (
		  ((!strcmp(tempNode->name1, type1)) && 
		  (!strcmp(tempNode->name2, type2)) && 
		  (!strcmp(tempNode->name3, type3)) &&
		  (!strcmp(tempNode->name4, type4))) ||
		  ((!strcmp(tempNode->name1, type2)) && 
		  (!strcmp(tempNode->name2, type3)) && 
		  (!strcmp(tempNode->name3, type4)) &&
		  (!strcmp(tempNode->name4, type1))) ||
		  ((!strcmp(tempNode->name1, type3)) && 
		  (!strcmp(tempNode->name2, type4)) && 
		  (!strcmp(tempNode->name3, type1)) &&
		  (!strcmp(tempNode->name4, type2))) ||
		  ((!strcmp(tempNode->name1, type2)) && 
		  (!strcmp(tempNode->name2, type3)) && 
		  (!strcmp(tempNode->name3, type4)) &&
		  (!strcmp(tempNode->name4, type1))) ||
		  ((!strcmp(tempNode->name1, type4)) && 
		  (!strcmp(tempNode->name2, type3)) && 
		  (!strcmp(tempNode->name3, type2)) &&
		  (!strcmp(tempNode->name4, type1))) ||
		  ((!strcmp(tempNode->name1, type3)) && 
		  (!strcmp(tempNode->name2, type2)) && 
		  (!strcmp(tempNode->name3, type1)) &&
		  (!strcmp(tempNode->name4, type4))) ||
		  ((!strcmp(tempNode->name1, type2)) && 
		  (!strcmp(tempNode->name2, type1)) && 
		  (!strcmp(tempNode->name3, type4)) &&
		  (!strcmp(tempNode->name4, type3))) ||
		  ((!strcmp(tempNode->name1, type1)) && 
		  (!strcmp(tempNode->name2, type4)) && 
		  (!strcmp(tempNode->name3, type3)) &&
		  (!strcmp(tempNode->name4, type2)))
	   ))

	{
		tempInt = 1;
	}
	if (
		 ((!strcmp(tempNode->name1, type1)) && 
		  (!strcmp(tempNode->name2, type2)) && 
		  (!strcmp(tempNode->name3, type3)) &&
		  (!strcmp(tempNode->name4, type4)) &&
		  (!strcmp(tempNode->effect1, effect1)) && 
		  (!strcmp(tempNode->effect2, effect2)) && 
		  (!strcmp(tempNode->effect3, effect3)) &&
		  (!strcmp(tempNode->effect4, effect4)) &&
		  (direction1 == tempNode->direction1) && 
		  (direction2 == tempNode->direction2) && 
		  (direction3 == tempNode->direction3) && 
		  (direction4 == tempNode->direction4)))
	{
		return 1;
	}

	if   ((!strcmp(tempNode->name1, type4)) && 
		  (!strcmp(tempNode->name2, type1)) && 
		  (!strcmp(tempNode->name3, type2)) &&
		  (!strcmp(tempNode->name4, type3)) &&
		  (!strcmp(tempNode->effect1, effect4)) && 
		  (!strcmp(tempNode->effect2, effect1)) &&
		  (!strcmp(tempNode->effect3, effect2)) && 
		  (!strcmp(tempNode->effect4, effect3)))
	{
		RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
	}
	else if (
		  (!strcmp(tempNode->name1, type3)) && 
		  (!strcmp(tempNode->name2, type4)) && 
		  (!strcmp(tempNode->name3, type1)) && 
		  (!strcmp(tempNode->name4, type2)) &&
		  (!strcmp(tempNode->effect1, effect3)) && 
		  (!strcmp(tempNode->effect2, effect4)) && 
		  (!strcmp(tempNode->effect3, effect1)) && 
		  (!strcmp(tempNode->effect4, effect2)))
	{
		RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
		RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
	}
	else if (
		  (!strcmp(tempNode->name1, type2)) && 
		  (!strcmp(tempNode->name2, type3)) && 
		  (!strcmp(tempNode->name3, type4)) &&
		  (!strcmp(tempNode->name4, type1)) &&
		  (!strcmp(tempNode->effect1, effect2)) && 
		  (!strcmp(tempNode->effect2, effect3)) && 
		  (!strcmp(tempNode->effect3, effect4)) && 
		  (!strcmp(tempNode->effect4, effect1)))
	{
		RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
		RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
		RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
	}
	else if (
		  (!strcmp(tempNode->name1, type4)) && 
		  (!strcmp(tempNode->name2, type3)) && 
		  (!strcmp(tempNode->name3, type2)) &&
		  (!strcmp(tempNode->name4, type1)) &&
		  (!strcmp(tempNode->effect1, effect4)) && 
		  (!strcmp(tempNode->effect2, effect3)) && 
		  (!strcmp(tempNode->effect3, effect2)) && 
		  (!strcmp(tempNode->effect4, effect1)))
	{
		FlipToInverse4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
	}
	else if (
		  (!strcmp(tempNode->name1, type3)) && 
		  (!strcmp(tempNode->name2, type2)) && 
		  (!strcmp(tempNode->name3, type1)) &&
		  (!strcmp(tempNode->name4, type4)) &&
		  (strcmp(type1, type3)) &&
		  (!strcmp(tempNode->effect1, effect3)) && 
		  (!strcmp(tempNode->effect2, effect2)) && 
		  (!strcmp(tempNode->effect3, effect1)) && 
		  (!strcmp(tempNode->effect4, effect4)))
	{
		RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
		FlipToInverse4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
	}
	else if (
		  (!strcmp(tempNode->name1, type2)) && 
		  (!strcmp(tempNode->name2, type1)) && 
		  (!strcmp(tempNode->name3, type4)) &&
		  (!strcmp(tempNode->name4, type3)) &&
		  (!strcmp(tempNode->effect1, effect2)) && 
		  (!strcmp(tempNode->effect2, effect1)) && 
		  (!strcmp(tempNode->effect3, effect4)) && 
		  (!strcmp(tempNode->effect4, effect3)))
	{
		RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
		RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
		FlipToInverse4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
	}
	else if (
		  (!strcmp(tempNode->name1, type1)) && 
		  (!strcmp(tempNode->name2, type4)) && 
		  (!strcmp(tempNode->name3, type3)) &&
		  (!strcmp(tempNode->name4, type2)) &&
		  (strcmp(type2, type4)) &&
		  (!strcmp(tempNode->effect1, effect1)) && 
		  (!strcmp(tempNode->effect2, effect4)) && 
		  (!strcmp(tempNode->effect3, effect3)) && 
		  (!strcmp(tempNode->effect4, effect2)))
	{
		RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
		RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
		RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
		FlipToInverse4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
	}

	if (
		 ((!strcmp(tempNode->name1, type1)) && 
		  (!strcmp(tempNode->name2, type2)) && 
		  (!strcmp(tempNode->name3, type3)) &&
		  (!strcmp(tempNode->name4, type4)) &&
		  (!strcmp(tempNode->effect1, effect1)) && 
		  (!strcmp(tempNode->effect2, effect2)) && 
		  (!strcmp(tempNode->effect3, effect3)) &&
		  (!strcmp(tempNode->effect4, effect4)) &&
		  (direction1 == tempNode->direction1) && 
		  (direction2 == tempNode->direction2) && 
		  (direction3 == tempNode->direction3) && 
		  (direction4 == tempNode->direction4)))
	{
		return 1;
	}
	else
	{
		if ((!strcmp(type1, type2)) || (!strcmp(type1, type3)) ||
			(!strcmp(type1, type4)) || (!strcmp(type2, type3)) || 
			(!strcmp(type2, type4)) || (!strcmp(type3, type4)))
		{
			//check for symmetry and flip
			if ((!strcmp(type2, type4)) &&
			//(!strcmp(effect1, effect3)) &&
			((direction1 + direction4) == 0) &&
			((direction2 + direction3) == 0))
			{
				strcpy(temp, effect1);
				strcpy(effect1, effect4);
				strcpy(effect4, temp);
				strcpy(temp, effect2);
				strcpy(effect2, effect3);
				strcpy(effect3, temp);
			}
			else if ((!strcmp(type1, type3)) &&
				//(!strcmp(effect2, effect3)) &&
				 ((direction1 + direction2) == 0) &&
				 ((direction4 + direction3) == 0))
			{
				strcpy(temp, effect1);
				strcpy(effect1, effect2);
				strcpy(effect2, temp);
				strcpy(temp, effect3);
				strcpy(effect3, effect4);
				strcpy(effect4, temp);
			}
		}		

		if (
		 ((!strcmp(tempNode->name1, type1)) && 
		  (!strcmp(tempNode->name2, type2)) && 
		  (!strcmp(tempNode->name3, type3)) &&
		  (!strcmp(tempNode->name4, type4)) &&
		  (!strcmp(tempNode->effect1, effect1)) && 
		  (!strcmp(tempNode->effect2, effect2)) && 
		  (!strcmp(tempNode->effect3, effect3)) &&
		  (!strcmp(tempNode->effect4, effect4)) &&
		  (direction1 == tempNode->direction1) && 
		  (direction2 == tempNode->direction2) && 
		  (direction3 == tempNode->direction3) && 
		  (direction4 == tempNode->direction4)))
		{
			return 1;
		}

		if   ((!strcmp(tempNode->name1, type4)) && 
		  (!strcmp(tempNode->name2, type1)) && 
		  (!strcmp(tempNode->name3, type2)) &&
		  (!strcmp(tempNode->name4, type3)) &&
		  (!strcmp(tempNode->effect1, effect4)) && 
		  (!strcmp(tempNode->effect2, effect1)) &&
		  (!strcmp(tempNode->effect3, effect2)) && 
		  (!strcmp(tempNode->effect4, effect3)))
		{
			RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
		}
		else if (
		  (!strcmp(tempNode->name1, type3)) && 
		  (!strcmp(tempNode->name2, type4)) && 
		  (!strcmp(tempNode->name3, type1)) && 
		  (!strcmp(tempNode->name4, type2)) &&
		  (!strcmp(tempNode->effect1, effect3)) && 
		  (!strcmp(tempNode->effect2, effect4)) && 
		  (!strcmp(tempNode->effect3, effect1)) && 
		  (!strcmp(tempNode->effect4, effect2)))
		{
			RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
			RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
		}
		else if (
		  (!strcmp(tempNode->name1, type2)) && 
		  (!strcmp(tempNode->name2, type3)) && 
		  (!strcmp(tempNode->name3, type4)) &&
		  (!strcmp(tempNode->name4, type1)) &&
		  (!strcmp(tempNode->effect1, effect2)) && 
		  (!strcmp(tempNode->effect2, effect3)) && 
		  (!strcmp(tempNode->effect3, effect4)) && 
		  (!strcmp(tempNode->effect4, effect1)))
		{
			RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
			RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
			RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
		}
		else if (
		  (!strcmp(tempNode->name1, type4)) && 
		  (!strcmp(tempNode->name2, type3)) && 
		  (!strcmp(tempNode->name3, type2)) &&
		  (!strcmp(tempNode->name4, type1)) &&
		  (!strcmp(tempNode->effect1, effect4)) && 
		  (!strcmp(tempNode->effect2, effect3)) && 
		  (!strcmp(tempNode->effect3, effect2)) && 
		  (!strcmp(tempNode->effect4, effect1)))
		{
			FlipToInverse4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
		}
		else if (
		  (!strcmp(tempNode->name1, type3)) && 
		  (!strcmp(tempNode->name2, type2)) && 
		  (!strcmp(tempNode->name3, type1)) &&
		  (!strcmp(tempNode->name4, type4)) &&
		  (strcmp(type1, type3)) &&
		  (!strcmp(tempNode->effect1, effect3)) && 
		  (!strcmp(tempNode->effect2, effect2)) && 
		  (!strcmp(tempNode->effect3, effect1)) && 
		  (!strcmp(tempNode->effect4, effect4)))
		{
			RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
			FlipToInverse4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
		}
		else if (
		  (!strcmp(tempNode->name1, type2)) && 
		  (!strcmp(tempNode->name2, type1)) && 
		  (!strcmp(tempNode->name3, type4)) &&
		  (!strcmp(tempNode->name4, type3)) &&
		  (!strcmp(tempNode->effect1, effect2)) && 
		  (!strcmp(tempNode->effect2, effect1)) && 
		  (!strcmp(tempNode->effect3, effect4)) && 
		  (!strcmp(tempNode->effect4, effect3)))
		{
			RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
			RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
			FlipToInverse4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
		}
		else if (
		  (!strcmp(tempNode->name1, type1)) && 
		  (!strcmp(tempNode->name2, type4)) && 
		  (!strcmp(tempNode->name3, type3)) &&
		  (!strcmp(tempNode->name4, type2)) &&
		  (strcmp(type2, type4)) &&
		  (!strcmp(tempNode->effect1, effect1)) && 
		  (!strcmp(tempNode->effect2, effect4)) && 
		  (!strcmp(tempNode->effect3, effect3)) && 
		  (!strcmp(tempNode->effect4, effect2)))
		{
			RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
			RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
			RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
			FlipToInverse4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
		}

		if (
		 ((!strcmp(tempNode->name1, type1)) && 
		  (!strcmp(tempNode->name2, type2)) && 
		  (!strcmp(tempNode->name3, type3)) &&
		  (!strcmp(tempNode->name4, type4)) &&
		  (!strcmp(tempNode->effect1, effect1)) && 
		  (!strcmp(tempNode->effect2, effect2)) && 
		  (!strcmp(tempNode->effect3, effect3)) &&
		  (!strcmp(tempNode->effect4, effect4)) &&
		  (direction1 == tempNode->direction1) && 
		  (direction2 == tempNode->direction2) && 
		  (direction3 == tempNode->direction3) && 
		  (direction4 == tempNode->direction4)))
		{
			return 1;
		}
		return 0;
	}
}
int TheSame4Names(MOTIF4* tempNode, 
				char* name1, char* name2, char* name3, char* name4,
				char* type1, char* type2, char* type3, char* type4,
				char* effect1, char* effect2, char* effect3, char* effect4,
				int& direction1, int& direction2, int& direction3, int& direction4)
{
	int tempInt;
	char temp[100];
	if (
		  ((!strcmp(tempNode->name1, name1)) && 
		  (!strcmp(tempNode->name2, name2)) && 
		  (!strcmp(tempNode->name3, name3)) &&
		  (!strcmp(tempNode->name4, name4))) ||
		  ((!strcmp(tempNode->name1, name2)) && 
		  (!strcmp(tempNode->name2, name3)) && 
		  (!strcmp(tempNode->name3, name4)) &&
		  (!strcmp(tempNode->name4, name1))) ||
		  ((!strcmp(tempNode->name1, name3)) && 
		  (!strcmp(tempNode->name2, name4)) && 
		  (!strcmp(tempNode->name3, name1)) &&
		  (!strcmp(tempNode->name4, name2))) ||
		  ((!strcmp(tempNode->name1, name2)) && 
		  (!strcmp(tempNode->name2, name3)) && 
		  (!strcmp(tempNode->name3, name4)) &&
		  (!strcmp(tempNode->name4, name1))) ||
		  ((!strcmp(tempNode->name1, name4)) && 
		  (!strcmp(tempNode->name2, name3)) && 
		  (!strcmp(tempNode->name3, name2)) &&
		  (!strcmp(tempNode->name4, name1))) ||
		  ((!strcmp(tempNode->name1, name3)) && 
		  (!strcmp(tempNode->name2, name2)) && 
		  (!strcmp(tempNode->name3, name1)) &&
		  (!strcmp(tempNode->name4, name4))) ||
		  ((!strcmp(tempNode->name1, name2)) && 
		  (!strcmp(tempNode->name2, name1)) && 
		  (!strcmp(tempNode->name3, name4)) &&
		  (!strcmp(tempNode->name4, name3))) ||
		  ((!strcmp(tempNode->name1, name1)) && 
		  (!strcmp(tempNode->name2, name4)) && 
		  (!strcmp(tempNode->name3, name3)) &&
		  (!strcmp(tempNode->name4, name2)))
	   )

	{
		tempInt = 1;
	}

	if (
		 ((!strcmp(tempNode->name1, type1)) && 
		  (!strcmp(tempNode->name2, type2)) && 
		  (!strcmp(tempNode->name3, type3)) &&
		  (!strcmp(tempNode->name4, type4)) &&
		  (!strcmp(tempNode->effect1, effect1)) && 
		  (!strcmp(tempNode->effect2, effect2)) && 
		  (!strcmp(tempNode->effect3, effect3)) &&
		  (!strcmp(tempNode->effect4, effect4)) &&
		  (direction1 == tempNode->direction1) && 
		  (direction2 == tempNode->direction2) && 
		  (direction3 == tempNode->direction3) && 
		  (direction4 == tempNode->direction4)))
	{
		return 1;
	}

	if   ((!strcmp(tempNode->name1, type4)) && 
		  (!strcmp(tempNode->name2, type1)) && 
		  (!strcmp(tempNode->name3, type2)) &&
		  (!strcmp(tempNode->name4, type3)) &&
		  (!strcmp(tempNode->effect1, effect4)) && 
		  (!strcmp(tempNode->effect2, effect1)) &&
		  (!strcmp(tempNode->effect3, effect2)) && 
		  (!strcmp(tempNode->effect4, effect3)))
	{
		RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
	}
	else if (
		  (!strcmp(tempNode->name1, type3)) && 
		  (!strcmp(tempNode->name2, type4)) && 
		  (!strcmp(tempNode->name3, type1)) && 
		  (!strcmp(tempNode->name4, type2)) &&
		  (!strcmp(tempNode->effect1, effect3)) && 
		  (!strcmp(tempNode->effect2, effect4)) && 
		  (!strcmp(tempNode->effect3, effect1)) && 
		  (!strcmp(tempNode->effect4, effect2)))
	{
		RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
		RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
	}
	else if (
		  (!strcmp(tempNode->name1, type2)) && 
		  (!strcmp(tempNode->name2, type3)) && 
		  (!strcmp(tempNode->name3, type4)) &&
		  (!strcmp(tempNode->name4, type1)) &&
		  (!strcmp(tempNode->effect1, effect2)) && 
		  (!strcmp(tempNode->effect2, effect3)) && 
		  (!strcmp(tempNode->effect3, effect4)) && 
		  (!strcmp(tempNode->effect4, effect1)))
	{
		RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
		RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
		RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
	}
	else if (
		  (!strcmp(tempNode->name1, type4)) && 
		  (!strcmp(tempNode->name2, type3)) && 
		  (!strcmp(tempNode->name3, type2)) &&
		  (!strcmp(tempNode->name4, type1)) &&
		  (!strcmp(tempNode->effect1, effect4)) && 
		  (!strcmp(tempNode->effect2, effect3)) && 
		  (!strcmp(tempNode->effect3, effect2)) && 
		  (!strcmp(tempNode->effect4, effect1)))
	{
		FlipToInverse4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
	}
	else if (
		  (!strcmp(tempNode->name1, type3)) && 
		  (!strcmp(tempNode->name2, type2)) && 
		  (!strcmp(tempNode->name3, type1)) &&
		  (!strcmp(tempNode->name4, type4)) &&
		  (strcmp(type1, type3)) &&
		  (!strcmp(tempNode->effect1, effect3)) && 
		  (!strcmp(tempNode->effect2, effect2)) && 
		  (!strcmp(tempNode->effect3, effect1)) && 
		  (!strcmp(tempNode->effect4, effect4)))
	{
		RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
		FlipToInverse4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
	}
	else if (
		  (!strcmp(tempNode->name1, type2)) && 
		  (!strcmp(tempNode->name2, type1)) && 
		  (!strcmp(tempNode->name3, type4)) &&
		  (!strcmp(tempNode->name4, type3)) &&
		  (!strcmp(tempNode->effect1, effect2)) && 
		  (!strcmp(tempNode->effect2, effect1)) && 
		  (!strcmp(tempNode->effect3, effect4)) && 
		  (!strcmp(tempNode->effect4, effect3)))
	{
		RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
		RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
		FlipToInverse4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
	}
	else if (
		  (!strcmp(tempNode->name1, type1)) && 
		  (!strcmp(tempNode->name2, type4)) && 
		  (!strcmp(tempNode->name3, type3)) &&
		  (!strcmp(tempNode->name4, type2)) &&
		  (strcmp(type2, type4)) &&
		  (!strcmp(tempNode->effect1, effect1)) && 
		  (!strcmp(tempNode->effect2, effect4)) && 
		  (!strcmp(tempNode->effect3, effect3)) && 
		  (!strcmp(tempNode->effect4, effect2)))
	{
		RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
		RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
		RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
		FlipToInverse4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
	}

	if (
		 ((!strcmp(tempNode->name1, type1)) && 
		  (!strcmp(tempNode->name2, type2)) && 
		  (!strcmp(tempNode->name3, type3)) &&
		  (!strcmp(tempNode->name4, type4)) &&
		  (!strcmp(tempNode->effect1, effect1)) && 
		  (!strcmp(tempNode->effect2, effect2)) && 
		  (!strcmp(tempNode->effect3, effect3)) &&
		  (!strcmp(tempNode->effect4, effect4)) &&
		  (direction1 == tempNode->direction1) && 
		  (direction2 == tempNode->direction2) && 
		  (direction3 == tempNode->direction3) && 
		  (direction4 == tempNode->direction4)))
	{
		return 1;
	}
	else
	{
		if ((!strcmp(type1, type2)) || (!strcmp(type1, type3)) ||
			(!strcmp(type1, type4)) || (!strcmp(type2, type3)) || 
			(!strcmp(type2, type4)) || (!strcmp(type3, type4)))
		{
			//check for symmetry and flip
			if ((!strcmp(type2, type4)) &&
			//(!strcmp(effect1, effect3)) &&
			((direction1 + direction4) == 0) &&
			((direction2 + direction3) == 0))
			{
				strcpy(temp, effect1);
				strcpy(effect1, effect4);
				strcpy(effect4, temp);
				strcpy(temp, effect2);
				strcpy(effect2, effect3);
				strcpy(effect3, temp);
			}
			else if ((!strcmp(type1, type3)) &&
				//(!strcmp(effect2, effect3)) &&
				 ((direction1 + direction2) == 0) &&
				 ((direction4 + direction3) == 0))
			{
				strcpy(temp, effect1);
				strcpy(effect1, effect2);
				strcpy(effect2, temp);
				strcpy(temp, effect3);
				strcpy(effect3, effect4);
				strcpy(effect4, temp);
			}
		}		

		if (
		 ((!strcmp(tempNode->name1, type1)) && 
		  (!strcmp(tempNode->name2, type2)) && 
		  (!strcmp(tempNode->name3, type3)) &&
		  (!strcmp(tempNode->name4, type4)) &&
		  (!strcmp(tempNode->effect1, effect1)) && 
		  (!strcmp(tempNode->effect2, effect2)) && 
		  (!strcmp(tempNode->effect3, effect3)) &&
		  (!strcmp(tempNode->effect4, effect4)) &&
		  (direction1 == tempNode->direction1) && 
		  (direction2 == tempNode->direction2) && 
		  (direction3 == tempNode->direction3) && 
		  (direction4 == tempNode->direction4)))
		{
			return 1;
		}

		if   ((!strcmp(tempNode->name1, type4)) && 
		  (!strcmp(tempNode->name2, type1)) && 
		  (!strcmp(tempNode->name3, type2)) &&
		  (!strcmp(tempNode->name4, type3)) &&
		  (!strcmp(tempNode->effect1, effect4)) && 
		  (!strcmp(tempNode->effect2, effect1)) &&
		  (!strcmp(tempNode->effect3, effect2)) && 
		  (!strcmp(tempNode->effect4, effect3)))
		{
			RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
		}
		else if (
		  (!strcmp(tempNode->name1, type3)) && 
		  (!strcmp(tempNode->name2, type4)) && 
		  (!strcmp(tempNode->name3, type1)) && 
		  (!strcmp(tempNode->name4, type2)) &&
		  (!strcmp(tempNode->effect1, effect3)) && 
		  (!strcmp(tempNode->effect2, effect4)) && 
		  (!strcmp(tempNode->effect3, effect1)) && 
		  (!strcmp(tempNode->effect4, effect2)))
		{
			RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
			RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
		}
		else if (
		  (!strcmp(tempNode->name1, type2)) && 
		  (!strcmp(tempNode->name2, type3)) && 
		  (!strcmp(tempNode->name3, type4)) &&
		  (!strcmp(tempNode->name4, type1)) &&
		  (!strcmp(tempNode->effect1, effect2)) && 
		  (!strcmp(tempNode->effect2, effect3)) && 
		  (!strcmp(tempNode->effect3, effect4)) && 
		  (!strcmp(tempNode->effect4, effect1)))
		{
			RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
			RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
			RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
		}
		else if (
		  (!strcmp(tempNode->name1, type4)) && 
		  (!strcmp(tempNode->name2, type3)) && 
		  (!strcmp(tempNode->name3, type2)) &&
		  (!strcmp(tempNode->name4, type1)) &&
		  (!strcmp(tempNode->effect1, effect4)) && 
		  (!strcmp(tempNode->effect2, effect3)) && 
		  (!strcmp(tempNode->effect3, effect2)) && 
		  (!strcmp(tempNode->effect4, effect1)))
		{
			FlipToInverse4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
		}
		else if (
		  (!strcmp(tempNode->name1, type3)) && 
		  (!strcmp(tempNode->name2, type2)) && 
		  (!strcmp(tempNode->name3, type1)) &&
		  (!strcmp(tempNode->name4, type4)) &&
		  (strcmp(type1, type3)) &&
		  (!strcmp(tempNode->effect1, effect3)) && 
		  (!strcmp(tempNode->effect2, effect2)) && 
		  (!strcmp(tempNode->effect3, effect1)) && 
		  (!strcmp(tempNode->effect4, effect4)))
		{
			RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
			FlipToInverse4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
		}
		else if (
		  (!strcmp(tempNode->name1, type2)) && 
		  (!strcmp(tempNode->name2, type1)) && 
		  (!strcmp(tempNode->name3, type4)) &&
		  (!strcmp(tempNode->name4, type3)) &&
		  (!strcmp(tempNode->effect1, effect2)) && 
		  (!strcmp(tempNode->effect2, effect1)) && 
		  (!strcmp(tempNode->effect3, effect4)) && 
		  (!strcmp(tempNode->effect4, effect3)))
		{
			RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
			RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
			FlipToInverse4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
		}
		else if (
		  (!strcmp(tempNode->name1, type1)) && 
		  (!strcmp(tempNode->name2, type4)) && 
		  (!strcmp(tempNode->name3, type3)) &&
		  (!strcmp(tempNode->name4, type2)) &&
		  (strcmp(type2, type4)) &&
		  (!strcmp(tempNode->effect1, effect1)) && 
		  (!strcmp(tempNode->effect2, effect4)) && 
		  (!strcmp(tempNode->effect3, effect3)) && 
		  (!strcmp(tempNode->effect4, effect2)))
		{
			RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
			RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
			RotateRight4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
			FlipToInverse4(type1, type2, type3, type4, 
			         effect1, effect2, effect3, effect4,
				     direction1, direction2, direction3, direction4);
		}

		if (
		 ((!strcmp(tempNode->name1, type1)) && 
		  (!strcmp(tempNode->name2, type2)) && 
		  (!strcmp(tempNode->name3, type3)) &&
		  (!strcmp(tempNode->name4, type4)) &&
		  (!strcmp(tempNode->effect1, effect1)) && 
		  (!strcmp(tempNode->effect2, effect2)) && 
		  (!strcmp(tempNode->effect3, effect3)) &&
		  (!strcmp(tempNode->effect4, effect4)) &&
		  (direction1 == tempNode->direction1) && 
		  (direction2 == tempNode->direction2) && 
		  (direction3 == tempNode->direction3) && 
		  (direction4 == tempNode->direction4)))
		{
			return 1;
		}
		return 0;
	}
}




int TheSame5TypesEffectsAndDirection(MOTIF5* tempNode, 
				char* type1, char* type2, char* type3, char* type4, char* type5,
				char* effect1, char* effect2, char* effect3, char* effect4, char* effect5,
				int& direction1, int& direction2, int& direction3, int& direction4, int& direction5)
{
	if (
		 ((!strcmp(tempNode->name1, type1)) && 
		  (!strcmp(tempNode->name2, type2)) && 
		  (!strcmp(tempNode->name3, type3)) &&
		  (!strcmp(tempNode->name4, type4)) &&
		  (!strcmp(tempNode->name5, type5)) &&
		  (!strcmp(tempNode->effect1, effect1)) && 
		  (!strcmp(tempNode->effect2, effect2)) && 
		  (!strcmp(tempNode->effect3, effect3)) &&
		  (!strcmp(tempNode->effect4, effect4)) &&
		  (!strcmp(tempNode->effect5, effect5)) &&
		  (direction1 == tempNode->direction1) && 
		  (direction2 == tempNode->direction2) && 
		  (direction3 == tempNode->direction3) && 
		  (direction4 == tempNode->direction4) &&
		  (direction5 == tempNode->direction5)))
	{
		return 1;
	}

	if   ((!strcmp(tempNode->name1, type5)) && 
		  (!strcmp(tempNode->name2, type1)) && 
		  (!strcmp(tempNode->name3, type2)) &&
		  (!strcmp(tempNode->name4, type3)) &&
		  (!strcmp(tempNode->name5, type4)) &&
		  (!strcmp(tempNode->effect1, effect5)) && 
		  (!strcmp(tempNode->effect2, effect1)) &&
		  (!strcmp(tempNode->effect3, effect2)) && 
		  (!strcmp(tempNode->effect4, effect3)) &&
		  (!strcmp(tempNode->effect5, effect4)))
	{
		RotateRight5(type1, type2, type3, type4, type5,
			         effect1, effect2, effect3, effect4, effect5,
				     direction1, direction2, direction3, direction4, direction5);
	}
	else if (
		  (!strcmp(tempNode->name1, type4)) && 
		  (!strcmp(tempNode->name2, type5)) && 
		  (!strcmp(tempNode->name3, type1)) && 
		  (!strcmp(tempNode->name4, type2)) &&
		  (!strcmp(tempNode->name5, type3)) &&
		  (!strcmp(tempNode->effect1, effect4)) && 
		  (!strcmp(tempNode->effect2, effect5)) && 
		  (!strcmp(tempNode->effect3, effect1)) && 
		  (!strcmp(tempNode->effect4, effect2)) && 
		  (!strcmp(tempNode->effect5, effect3)))
	{
		RotateRight5(type1, type2, type3, type4, type5,
			         effect1, effect2, effect3, effect4, effect5,
				     direction1, direction2, direction3, direction4, direction5);
		RotateRight5(type1, type2, type3, type4, type5,
			         effect1, effect2, effect3, effect4, effect5,
				     direction1, direction2, direction3, direction4, direction5);
	}
	else if (
		  (!strcmp(tempNode->name1, type3)) && 
		  (!strcmp(tempNode->name2, type4)) && 
		  (!strcmp(tempNode->name3, type5)) && 
		  (!strcmp(tempNode->name4, type1)) &&
		  (!strcmp(tempNode->name5, type2)) &&
		  (!strcmp(tempNode->effect1, effect3)) && 
		  (!strcmp(tempNode->effect2, effect4)) && 
		  (!strcmp(tempNode->effect3, effect5)) && 
		  (!strcmp(tempNode->effect4, effect1)) && 
		  (!strcmp(tempNode->effect5, effect2)))
	{
		RotateRight5(type1, type2, type3, type4, type5,
			         effect1, effect2, effect3, effect4, effect5,
				     direction1, direction2, direction3, direction4, direction5);
		RotateRight5(type1, type2, type3, type4, type5,
			         effect1, effect2, effect3, effect4, effect5,
				     direction1, direction2, direction3, direction4, direction5);
		RotateRight5(type1, type2, type3, type4, type5,
			         effect1, effect2, effect3, effect4, effect5,
				     direction1, direction2, direction3, direction4, direction5);
	}
	else if (
		  (!strcmp(tempNode->name1, type2)) && 
		  (!strcmp(tempNode->name2, type3)) && 
		  (!strcmp(tempNode->name3, type4)) && 
		  (!strcmp(tempNode->name4, type5)) &&
		  (!strcmp(tempNode->name5, type1)) &&
		  (!strcmp(tempNode->effect1, effect2)) && 
		  (!strcmp(tempNode->effect2, effect3)) && 
		  (!strcmp(tempNode->effect3, effect4)) && 
		  (!strcmp(tempNode->effect4, effect5)) && 
		  (!strcmp(tempNode->effect5, effect1)))
	{
		RotateRight5(type1, type2, type3, type4, type5,
			         effect1, effect2, effect3, effect4, effect5,
				     direction1, direction2, direction3, direction4, direction5);
		RotateRight5(type1, type2, type3, type4, type5,
			         effect1, effect2, effect3, effect4, effect5,
				     direction1, direction2, direction3, direction4, direction5);
		RotateRight5(type1, type2, type3, type4, type5,
			         effect1, effect2, effect3, effect4, effect5,
				     direction1, direction2, direction3, direction4, direction5);
		RotateRight5(type1, type2, type3, type4, type5,
			         effect1, effect2, effect3, effect4, effect5,
				     direction1, direction2, direction3, direction4, direction5);
	}
	else if (
		  (!strcmp(tempNode->name1, type5)) && 
		  (!strcmp(tempNode->name2, type4)) && 
		  (!strcmp(tempNode->name3, type3)) && 
		  (!strcmp(tempNode->name4, type2)) &&
		  (!strcmp(tempNode->name5, type1)) &&
		  (!strcmp(tempNode->effect1, effect5)) && 
		  (!strcmp(tempNode->effect2, effect4)) && 
		  (!strcmp(tempNode->effect3, effect3)) && 
		  (!strcmp(tempNode->effect4, effect2)) && 
		  (!strcmp(tempNode->effect5, effect1)))
	{
		FlipToInverse5(type1, type2, type3, type4, type5,
			         effect1, effect2, effect3, effect4, effect5,
				     direction1, direction2, direction3, direction4, direction5);
	}
	else if (
		  (!strcmp(tempNode->name1, type4)) && 
		  (!strcmp(tempNode->name2, type3)) && 
		  (!strcmp(tempNode->name3, type2)) && 
		  (!strcmp(tempNode->name4, type1)) &&
		  (!strcmp(tempNode->name5, type5)) &&
		  (!strcmp(tempNode->effect1, effect4)) && 
		  (!strcmp(tempNode->effect2, effect3)) && 
		  (!strcmp(tempNode->effect3, effect2)) && 
		  (!strcmp(tempNode->effect4, effect1)) && 
		  (!strcmp(tempNode->effect5, effect5)))
	{
		RotateRight5(type1, type2, type3, type4, type5,
			         effect1, effect2, effect3, effect4, effect5,
				     direction1, direction2, direction3, direction4, direction5);
		FlipToInverse5(type1, type2, type3, type4, type5,
			         effect1, effect2, effect3, effect4, effect5,
				     direction1, direction2, direction3, direction4, direction5);
	}
	else if (
		  (!strcmp(tempNode->name1, type3)) && 
		  (!strcmp(tempNode->name2, type2)) && 
		  (!strcmp(tempNode->name3, type1)) && 
		  (!strcmp(tempNode->name4, type5)) &&
		  (!strcmp(tempNode->name5, type4)) &&
		  (!strcmp(tempNode->effect1, effect3)) && 
		  (!strcmp(tempNode->effect2, effect2)) && 
		  (!strcmp(tempNode->effect3, effect1)) && 
		  (!strcmp(tempNode->effect4, effect5)) && 
		  (!strcmp(tempNode->effect5, effect4)))
	{
		RotateRight5(type1, type2, type3, type4, type5,
			         effect1, effect2, effect3, effect4, effect5,
				     direction1, direction2, direction3, direction4, direction5);
		RotateRight5(type1, type2, type3, type4, type5,
			         effect1, effect2, effect3, effect4, effect5,
				     direction1, direction2, direction3, direction4, direction5);
		FlipToInverse5(type1, type2, type3, type4, type5,
			         effect1, effect2, effect3, effect4, effect5,
				     direction1, direction2, direction3, direction4, direction5);
	}
	else if (
		  (!strcmp(tempNode->name1, type2)) && 
		  (!strcmp(tempNode->name2, type1)) && 
		  (!strcmp(tempNode->name3, type5)) && 
		  (!strcmp(tempNode->name4, type4)) &&
		  (!strcmp(tempNode->name5, type3)) &&
		  (!strcmp(tempNode->effect1, effect2)) && 
		  (!strcmp(tempNode->effect2, effect1)) && 
		  (!strcmp(tempNode->effect3, effect5)) && 
		  (!strcmp(tempNode->effect4, effect4)) && 
		  (!strcmp(tempNode->effect5, effect3)))
	{
		RotateRight5(type1, type2, type3, type4, type5,
			         effect1, effect2, effect3, effect4, effect5,
				     direction1, direction2, direction3, direction4, direction5);
		RotateRight5(type1, type2, type3, type4, type5,
			         effect1, effect2, effect3, effect4, effect5,
				     direction1, direction2, direction3, direction4, direction5);
		RotateRight5(type1, type2, type3, type4, type5,
			         effect1, effect2, effect3, effect4, effect5,
				     direction1, direction2, direction3, direction4, direction5);
		FlipToInverse5(type1, type2, type3, type4, type5,
			         effect1, effect2, effect3, effect4, effect5,
				     direction1, direction2, direction3, direction4, direction5);
	}
	else if (
		  (!strcmp(tempNode->name1, type1)) && 
		  (!strcmp(tempNode->name2, type5)) && 
		  (!strcmp(tempNode->name3, type4)) && 
		  (!strcmp(tempNode->name4, type3)) &&
		  (!strcmp(tempNode->name5, type2)) &&
		  (!strcmp(tempNode->effect1, effect1)) && 
		  (!strcmp(tempNode->effect2, effect5)) && 
		  (!strcmp(tempNode->effect3, effect4)) && 
		  (!strcmp(tempNode->effect4, effect3)) && 
		  (!strcmp(tempNode->effect5, effect2)))
	{
		RotateRight5(type1, type2, type3, type4, type5,
			         effect1, effect2, effect3, effect4, effect5,
				     direction1, direction2, direction3, direction4, direction5);
		RotateRight5(type1, type2, type3, type4, type5,
			         effect1, effect2, effect3, effect4, effect5,
				     direction1, direction2, direction3, direction4, direction5);
		RotateRight5(type1, type2, type3, type4, type5,
			         effect1, effect2, effect3, effect4, effect5,
				     direction1, direction2, direction3, direction4, direction5);
		RotateRight5(type1, type2, type3, type4, type5,
			         effect1, effect2, effect3, effect4, effect5,
				     direction1, direction2, direction3, direction4, direction5);
		FlipToInverse5(type1, type2, type3, type4, type5,
			         effect1, effect2, effect3, effect4, effect5,
				     direction1, direction2, direction3, direction4, direction5);
	}
	

	if (
		 ((!strcmp(tempNode->name1, type1)) && 
		  (!strcmp(tempNode->name2, type2)) && 
		  (!strcmp(tempNode->name3, type3)) &&
		  (!strcmp(tempNode->name4, type4)) &&
		  (!strcmp(tempNode->name5, type5)) &&
		  (!strcmp(tempNode->effect1, effect1)) && 
		  (!strcmp(tempNode->effect2, effect2)) && 
		  (!strcmp(tempNode->effect3, effect3)) &&
		  (!strcmp(tempNode->effect4, effect4)) &&
		  (!strcmp(tempNode->effect5, effect5)) &&
		  (direction1 == tempNode->direction1) && 
		  (direction2 == tempNode->direction2) && 
		  (direction3 == tempNode->direction3) && 
		  (direction4 == tempNode->direction4) &&
		  (direction5 == tempNode->direction5)))
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

void CTestSVGDlg::OnBnClickedButtonBasedOnConnectivity()
{
	
	ShutOffAllButtons();

	ProgressCount2 = 1;

	// start the thread that computes 
	pThreadCreateWebSite = AfxBeginThread(BasedOnConnectivityThread,
								GetSafeHwnd(), 
								THREAD_PRIORITY_BELOW_NORMAL);
}

UINT BasedOnConnectivityThread(LPVOID pParam)
{
	CreateReducedNetworks(pParam);
	ComputeStatsForReducedNetworks(pParam);

	return 0;
}

UINT FromSourceNodesThread(LPVOID pParam)
{
	CreateSubetworksFromSourceNodes(pParam);
	ComputeStatsForSubnetworksFromSourceNodes(pParam);

	return 0;
}

void ComputeStatsForSubnetworksFromSourceNodes(LPVOID pParam)
{
	int i;
	int j;
	int ret;
	int flag;
	char fileName[300];
	char name[300][300];
	int k = 0;
	MOLECULE* startNode;
	ofstream out1;
	ofstream out;

	out1.open("dips.htm");
	out1 << "<html><body><table>" << endl;

	out.open("stats_for_steps_networks.htm");
	out << "<html><body><table>";

	startNode = MoleculesList;

	while (startNode)
	{
		flag = 0;
		if (FromSourceChoices.type == "Type")
		{
			if (!strcmp(startNode->moleculeType, FromSourceChoices.name.GetBuffer()))
			{
				flag = 1;
			}
		}
		if (FromSourceChoices.type == "Name")
		{
			if (!strcmp(startNode->name, FromSourceChoices.name.GetBuffer()))
			{
				flag = 1;
			}
		}
		if (FromSourceChoices.type == "Location")
		{
			if (!strcmp(startNode->location, FromSourceChoices.name.GetBuffer()))
			{
				flag = 1;
			}
		}

		if (flag)
		{
			strcpy(name[k], startNode->name);
			k++;
		}
		startNode = startNode->next;
	}

	FreeNetwork();

	for (j = 0; j < k; j++)
	{
		out << "<tr><td>" << name[j] << "</td></tr>";
		out << "<tr><td>" << "steps";
		out << "</td><td>" << "interactions";
		out << "</td><td>" << "nodes";
		out << "</td><td>" << "positive links";
		out << "</td><td>" << "negative links";
		out << "</td><td>" << "neutral links";
		out << "</td><td>" << "CC";
		out << "</td><td>" << "GC"; 
		out << "</td><td>" << "CPL";
		out << "</td><td>" << "islands"; 
		out << "</td><td>" << "FBL3";
		out << "</td><td>" << "FBL4";
		out << "</td><td>" << "PFBL3";
		out << "</td><td>" << "PFBL4";
		out << "</td><td>" << "NFBL3";
		out << "</td><td>" << "NFBL4";
		out << "</td><td>" << "Scaffolds";
		out << "</td><td>" << "Bifans";
		out << "</td><td>" << "FFL3";
		out << "</td><td>" << "FFL4";
		out << "</td><td>" << "PFFL3";
		out << "</td><td>" << "PFFL4";
		out << "</td><td>" << "NFFL3";
		out << "</td><td>" << "NFFL4";
		out << "</td></tr>" << endl;

		for (i = 2; i <= FromSourceChoices.steps; i++)
		{	
			sprintf(fileName, "%s_sub_net_depth%d.sig", name[j], i);
			sprintf(MotifsMessage, "Searching for motifs in %s...", fileName);
			ret = LoadNetwork(fileName);
			ProgressCount2 = 0;
			CountDirectedCycles(3, pParam);
			ProgressCount2 = 0;
			CountDirectedCycles(4, pParam);
			ProgressCount2 = 0;
			CountScaffoldCycles(pParam);
			ProgressCount2 = 0;
			CountBifanCycles(pParam);
			ProgressCount2 = 0;
			CountConvergedCycles(3, pParam);
			ProgressCount2 = 0;
			CountConvergedCycles(4, pParam);
			CountNumberOfEffects();
				
			out << "<tr><td>" << i;
			out << "</td><td>" << NumberOfInteractions;
			out << "</td><td>" << NumberOfMolecules;
			out << "</td><td>" << CountPositives();
			out << "</td><td>" << CountNegatives();
			out << "</td><td>" << CountNeutrals();
			out << "</td><td>" << ComputeCC();
			out << "</td><td>" << ComputeGC();
			out << "</td><td>" << ComputeAvgPathLength();
			out << "</td><td>" << CountIslands();
			out << "</td><td>" << CountFeedbackLoops(3);
			out << "</td><td>" << CountFeedbackLoops(4);
			out << "</td><td>" << CountPositiveFeedbackLoops(3);
			out << "</td><td>" << CountPositiveFeedbackLoops(4);
			out << "</td><td>" << CountNegativeFeedbackLoops(3);
			out << "</td><td>" << CountNegativeFeedbackLoops(4);
			out << "</td><td>" << CountScaffolds();
			out << "</td><td>" << CountBifans();
			out << "</td><td>" << CountFeedforwardLoops(3);
			out << "</td><td>" << CountFeedforwardLoops(4);
			out << "</td><td>" << CountPositiveFeedforwardLoops(3);
			out << "</td><td>" << CountPositiveFeedforwardLoops(4);
			out << "</td><td>" << CountNegativeFeedforwardLoops(3);
			out << "</td><td>" << CountNegativeFeedforwardLoops(4);
			out << "</td></tr>" << endl;

			SortAndDumpMotifDensity(out1);

			FreeMotifs();		
			FreeNetwork();

			ProgressCount2++;
			sprintf(FromSourceNodesMessage, "Analyzed the file %s...", fileName);
			
			::PostMessage((HWND) pParam, WM_UPDATE_FROM_SOURCE_NODES_PROGRESS, 0, 0);

			if (ret == -1)
			{
				break;
			}
		}
	}
			
	out << "</TR>" << endl;	
	out << "</table></body></html>";
	out1 << "</table></body></html>";
	
	out.close();
	out1.close();
	

	ProgressCount2++;
	sprintf(FromSourceNodesMessage, "Done analyzing steps sub-networks...");
	::PostMessage((HWND) pParam, WM_THREAD_FROM_SOURCE_NODES_FINISHED, 0, 0);

}
void SortAndDumpMotifDensity(ofstream &out1)
{
	MOLECULE* tempNode;

	tempNode = MoleculesList;
	

	while (tempNode)
	{
		tempNode->appearInTotal = (float) ((tempNode->appearInBifans +
								  tempNode->appearInFeedbackLoops +
								  tempNode->appearInFeedforwardLoops) / NumberOfInteractions); //tempNode->linksCount;
		tempNode = tempNode->next;
	}

	SortMoleculeListBasedOnMotifs();

	tempNode = MoleculesList;

	out1 << "<tr>";
	while (tempNode)
	{
		out1 << "<td>"  << tempNode->appearInTotal << "</td>" << endl;
		tempNode = tempNode->next;
	}
	out1 << "</tr>" << endl;

	return;
}

void CreateSubetworksFromSourceNodes(LPVOID pParam)
{
	MOLECULE* startNode;
	int i, k;
	ofstream out;
	int count = 0;
	char fileName[100];
	int flag;
	startNode = MoleculesList;

	k = 0;

	while (startNode)
	{
		flag = 0;
		if (FromSourceChoices.type == "Type")
		{
			if (!strcmp(startNode->moleculeType, FromSourceChoices.name.GetBuffer()))
			{
				flag = 1;
			}
		}
		if (FromSourceChoices.type == "Name")
		{
			if (!strcmp(startNode->name, FromSourceChoices.name.GetBuffer()))
			{
				flag = 1;
			}
		}
		if (FromSourceChoices.type == "Location")
		{
			if (!strcmp(startNode->location, FromSourceChoices.name.GetBuffer()))
			{
				flag = 1;
			}
		}

		if (flag)
		{
			k++;

			ClearVisitedFlagForAllMolecules();

			for (i = 1; i <= FromSourceChoices.steps; i++)
			{	
				count = 0;

				if (FromSourceChoices.direction == "Forward")
				{
					count = ExpandSim(startNode, i, count);
				}
				else
				{
					count = ExpandReverseSim(startNode, i, count);
				}

				count = CountAllVisited();
				
				sprintf(fileName, "%s_sub_net_depth%d.sig", startNode->name, i);

				startNode->visited = 1;
			
				if (count != 1)
				{
					DumpAllVisited(fileName);
					ProgressCount2++;
					sprintf(FromSourceNodesMessage, "Created file %s...", fileName);
					::PostMessage((HWND) pParam, WM_UPDATE_FROM_SOURCE_NODES_PROGRESS, 0, 0);
				}
			}
		}
		startNode = startNode->next;
	}
}

void ComputeStatsForReducedNetworks(LPVOID pParam)
{
	int j;

	char fileName[100];
	int totalPositiveFeedback = 0;
	int totalNegativeFeedback = 0;
	int totalPositiveFeedforward = 0;
	int totalNegativeFeedforward = 0;

	if (DirLevel == 0)
	{
		DirLevel = 1;
	}
	else
	{
		chdir("..");	
	}
	mkdir("SNAVI_reduced");
	chdir("SNAVI_reduced");

	ofstream out;
	out.open("stats_for_reduced_networks.htm");
	out << "<html><body><table>";	
	out << "<tr><td>" << "allowed connectivity";
	out << "</td><td>" << "interactions";
	out << "</td><td>" << "nodes";
	out << "</td><td>" << "positive links";
	out << "</td><td>" << "negative links";
	out << "</td><td>" << "neutral links";
	out << "</td><td>" << "CC";
	out << "</td><td>" << "GC"; 
	out << "</td><td>" << "CPL";
	out << "</td><td>" << "islands"; 
	out << "</td><td>" << "FBL3";
	out << "</td><td>" << "FBL4";
	out << "</td><td>" << "PFBL3";
	out << "</td><td>" << "PFBL4";
	out << "</td><td>" << "NFBL3";
	out << "</td><td>" << "NFBL4";
	out << "</td><td>" << "Scaffolds";
	out << "</td><td>" << "Bifans";
	out << "</td><td>" << "FFL3";
	out << "</td><td>" << "FFL4";
	out << "</td><td>" << "PFFL3";
	out << "</td><td>" << "PFFL4";
	out << "</td><td>" << "NFFL3";
	out << "</td><td>" << "NFFL4";
	out << "</td></tr>" << endl;
		
	FreeNetwork();

	for (j = 4; j <= 50; j++)
	{
		sprintf(fileName, "reduced_net%d.sig", j);
		sprintf(MotifsMessage, "Searching for motifs in %s...", fileName);
		LoadNetwork(fileName);
		ProgressCount2 = 0;
		CountDirectedCycles(3, pParam);
		ProgressCount2 = 0;
		CountDirectedCycles(4, pParam);
		ProgressCount2 = 0;
		CountScaffoldCycles(pParam);
		ProgressCount2 = 0;
		CountBifanCycles(pParam);
		ProgressCount2 = 0;
		CountConvergedCycles(3, pParam);
		ProgressCount2 = 0;
		CountConvergedCycles(4, pParam);
		CountNumberOfEffects();

		if (CountIslands() == 1)
		{
			out << "<tr><td>" << j;
			out << "</td><td>" << NumberOfInteractions;
			out << "</td><td>" << NumberOfMolecules;
			out << "</td><td>" << CountPositives();
			out << "</td><td>" << CountNegatives();
			out << "</td><td>" << CountNeutrals();
			out << "</td><td>" << ComputeCC();
			out << "</td><td>" << ComputeGC();
			out << "</td><td>" << ComputeAvgPathLength();
			out << "</td><td>" << CountIslands();

			out << "</td><td>" << CountFeedbackLoops(3);
			out << "</td><td>" << CountFeedbackLoops(4);
			out << "</td><td>" << CountPositiveFeedbackLoops(3);
			out << "</td><td>" << CountPositiveFeedbackLoops(4);
			out << "</td><td>" << CountNegativeFeedbackLoops(3);
			out << "</td><td>" << CountNegativeFeedbackLoops(4);
			out << "</td><td>" << CountScaffolds();
			out << "</td><td>" << CountBifans();
			out << "</td><td>" << CountFeedforwardLoops(3);
			out << "</td><td>" << CountFeedforwardLoops(4);
			out << "</td><td>" << CountPositiveFeedforwardLoops(3);
			out << "</td><td>" << CountPositiveFeedforwardLoops(4);
			out << "</td><td>" << CountNegativeFeedforwardLoops(3);
			out << "</td><td>" << CountNegativeFeedforwardLoops(4);
			out << "</td></tr>" << endl;
		}
		else
		{
			out << "<tr><td>" << j;
			out << "</td><td>" << NumberOfInteractions;
			out << "</td><td>" << NumberOfMolecules;
			out << "</td><td>" << CountPositives();
			out << "</td><td>" << CountNegatives();
			out << "</td><td>" << CountNeutrals();
			out << "</td><td>" << ComputeCC();
			out << "</td><td>" << ComputeGC();
			out << "</td><td>" << ComputeAvgPathLength();
			out << "</td><td>" << CountIslands();
			out << "</td><td>" << CountFeedbackLoops(3);
			out << "</td><td>" << CountFeedbackLoops(4);
			out << "</td><td>" << CountPositiveFeedbackLoops(3);
			out << "</td><td>" << CountPositiveFeedbackLoops(4);
			out << "</td><td>" << CountNegativeFeedbackLoops(3);
			out << "</td><td>" << CountNegativeFeedbackLoops(4);
			out << "</td><td>" << CountScaffolds();
			out << "</td><td>" << CountBifans();
			out << "</td><td>" << CountFeedforwardLoops(3);
			out << "</td><td>" << CountFeedforwardLoops(4);
			out << "</td><td>" << CountPositiveFeedforwardLoops(3);
			out << "</td><td>" << CountPositiveFeedforwardLoops(4);
			out << "</td><td>" << CountNegativeFeedforwardLoops(3);
			out << "</td><td>" << CountNegativeFeedforwardLoops(4);
			out << "</td></tr>" << endl;
		}
	
		FreeMotifs();
		FreeNetwork();

		ProgressCount2++;
		
		sprintf(BasedOnConnectivityMessage, "Analyzed %d sub-networks out of 46...", j - 4);
		::PostMessage((HWND) pParam, WM_UPDATE_BASED_ON_CONNECTIVITY_PROGRESS, 0, 0);
	}
	out << "</table></body></html>";


	ProgressCount2++;
	strcpy(BasedOnConnectivityMessage, "Finished analyzing sub-networks based on connectivity...");
	LoadNetwork(OriginalNetworkName);
	::PostMessage((HWND) pParam, WM_THREAD_BASED_ON_CONNECTIVITY_FINISHED, 0, 0);
	
	out.close();
}

void CreateReducedNetworks(LPVOID pParam)
{
	INTERACTION* tempNode;
	MOLECULE* tempNode1;
	MOLECULE* tempNode2;
	ofstream out;
	int numberOfInteractions = 0;
	int j;
	char fileName[100];
	char pajekFileName[100];

	for (j = 4; j <= 50; j++)
	{
		numberOfInteractions = 0;

		sprintf(fileName, "reduced_net%d.sig", j);
		sprintf(pajekFileName, "reduced_net%d.net", j);
		
		out.open(fileName);

		tempNode = InteractionsList;
		while (tempNode)
		{
			tempNode1 = GetNodeBasedOnName(tempNode->source);
			tempNode2 = GetNodeBasedOnName(tempNode->target);

			if ((tempNode1->linksCount <= j) && (tempNode2->linksCount <= j))
			{
				numberOfInteractions++;
			}
			
			tempNode = tempNode->next;
		}

		ClearInteractionsFlag();

		tempNode = InteractionsList;

		while (tempNode)
		{
			tempNode1 = GetNodeBasedOnName(tempNode->source);
			tempNode2 = GetNodeBasedOnName(tempNode->target);

			if ((tempNode1->linksCount <= j) && (tempNode2->linksCount <= j))
			{
				out << tempNode->source << " " << tempNode->sourceAccHuman << " " << tempNode->sourceAccMouse << " " << tempNode->sourceType << " " << tempNode->sourceLocation << " " << tempNode->target << " " << tempNode->targetAccHuman << " " << tempNode->targetAccMouse << " ";
				out << tempNode->targetType << " " << tempNode->targetLocation << " " << tempNode->effect << " " << tempNode->typeOfInteraction << " " << tempNode->pmid << endl;
				tempNode->flag = 1;
			}

			tempNode = tempNode->next;
		}
		
		//DumpFlaggedInteractionsToPajek(pajekFileName);

		out.close();

		ProgressCount2++;
		sprintf(BasedOnConnectivityMessage, "Created %d sub-networks out of 46...", j - 4);
		::PostMessage((HWND) pParam, WM_UPDATE_BASED_ON_CONNECTIVITY_PROGRESS, 0, 0);
	}
}

void CTestSVGDlg::OnBnClickedButtonFromSourceNodes()
{
	int ret;

	CDialogSourceNodesSetup myDialog;

	ret = myDialog.DoModal();

	if (IDCANCEL == ret)
	{
		return;
	}

	FromSourceChoices.direction = myDialog.m_direction;
	FromSourceChoices.name = myDialog.m_name;
	FromSourceChoices.type = myDialog.m_type;
	FromSourceChoices.steps = myDialog.m_steps;

	ShutOffAllButtons();

	ProgressCount2 = 1;

	if (DirLevel == 0)
	{
		DirLevel = 1;
	}
	else
	{
		chdir("..");	
	}
	mkdir("SNAVI_from_sources");
	chdir("SNAVI_from_sources");

	// start the thread that computes 
	pThreadCreateWebSite = AfxBeginThread(FromSourceNodesThread,
								GetSafeHwnd(), 
								THREAD_PRIORITY_BELOW_NORMAL);
}

int CountPositives()
{
	INTERACTION* tempNode;
	int count = 0;

	tempNode = InteractionsList;

	while (tempNode)
	{
		if (!strcmp(tempNode->effect, "+"))
		{
			count++;
		}
		tempNode = tempNode->next;
	}

	return count;
}

int CountNegatives()
{
	INTERACTION* tempNode;
	int count = 0;

	tempNode = InteractionsList;

	while (tempNode)
	{
		if (!strcmp(tempNode->effect, "_"))
		{
			count++;
		}
		tempNode = tempNode->next;
	}

	return count;
}

int CountNeutrals()
{
	INTERACTION* tempNode;
	int count = 0;

	tempNode = InteractionsList;

	while (tempNode)
	{
		if (!strcmp(tempNode->effect, "0"))
		{
			count++;
		}
		tempNode = tempNode->next;
	}

	return count;
}

int CountFeedbackLoops(int size)
{
	MOTIF3* tempNode3;
	MOTIF4* tempNode4;
	int count = 0;
	if (size == 3)
	{
		tempNode3 = Motif3List;

		while (tempNode3)
		{
			if (tempNode3->type == 1)
			{
				count++;
			}
			tempNode3 = tempNode3->next;
		}
	}
	if (size == 4)
	{
		tempNode4 = Motif4List;

		while (tempNode4)
		{
			if (tempNode4->type == 1)
			{
				count++;
			}
			tempNode4 = tempNode4->next;
		}
	}

	return count;
}

int CountNegativeFeedbackLoops(int size)
{
	MOTIF3* tempNode3;
	MOTIF4* tempNode4;
	int count = 0;
	if (size == 3)
	{
		tempNode3 = Motif3List;

		while (tempNode3)
		{
			if (tempNode3->type == 1)
			{
				if (tempNode3->sign == -1)
				{
					count++;
				}
			}
			tempNode3 = tempNode3->next;
		}
	}
	if (size == 4)
	{
		tempNode4 = Motif4List;

		while (tempNode4)
		{
			if (tempNode4->type == 1)
			{
				if (tempNode4->sign == -1)
				{
					count++;
				}
			}
			tempNode4 = tempNode4->next;
		}
	}

	return count;
}

int CountPositiveFeedbackLoops(int size)
{
	MOTIF3* tempNode3;
	MOTIF4* tempNode4;
	int count = 0;
	if (size == 3)
	{
		tempNode3 = Motif3List;

		while (tempNode3)
		{
			if (tempNode3->type == 1)
			{
				if (tempNode3->sign == 1)
				{
					count++;
				}
			}
			tempNode3 = tempNode3->next;
		}
	}
	if (size == 4)
	{
		tempNode4 = Motif4List;

		while (tempNode4)
		{
			if (tempNode4->type == 1)
			{
				if (tempNode4->sign == 1)
				{
					count++;
				}
			}
			tempNode4 = tempNode4->next;
		}
	}

	return count;
}

int CountPositiveFeedforwardLoops(int size)
{
	MOTIF3* tempNode3;
	MOTIF4* tempNode4;
	int count = 0;
	if (size == 3)
	{
		tempNode3 = Motif3List;

		while (tempNode3)
		{
			if (tempNode3->type == 2)
			{
				if (tempNode3->sign == 1)
				{
					count++;
				}
			}
			tempNode3 = tempNode3->next;
		}
	}
	if (size == 4)
	{
		tempNode4 = Motif4List;

		while (tempNode4)
		{
			if (tempNode4->type == 2)
			{
				if (tempNode4->sign == 1)
				{
					count++;
				}
			}
			tempNode4 = tempNode4->next;
		}
	}

	return count;
}

int CountFeedforwardLoops(int size)
{
	MOTIF3* tempNode3;
	MOTIF4* tempNode4;
	int count = 0;
	if (size == 3)
	{
		tempNode3 = Motif3List;

		while (tempNode3)
		{
			if (tempNode3->type == 2)
			{
				count++;
			}
			tempNode3 = tempNode3->next;
		}
	}
	if (size == 4)
	{
		tempNode4 = Motif4List;

		while (tempNode4)
		{
			if (tempNode4->type == 2)
			{
				count++;
			}
			tempNode4 = tempNode4->next;
		}
	}

	return count;
}

int CountNegativeFeedforwardLoops(int size)
{
	MOTIF3* tempNode3;
	MOTIF4* tempNode4;
	int count = 0;
	if (size == 3)
	{
		tempNode3 = Motif3List;

		while (tempNode3)
		{
			if (tempNode3->type == 2)
			{
				if (tempNode3->sign == -1)
				{
					count++;
				}
			}
			tempNode3 = tempNode3->next;
		}
	}
	if (size == 4)
	{
		tempNode4 = Motif4List;

		while (tempNode4)
		{
			if (tempNode4->type == 2)
			{
				if (tempNode4->sign == -1)
				{
					count++;
				}
			}
			tempNode4 = tempNode4->next;
		}
	}

	return count;
}

int CountBifans(void)
{
	MOTIF4* tempNode4;
	int count = 0;
	
	tempNode4 = Motif4List;

	while (tempNode4)
	{
		if (tempNode4->type == 4)
		{
			count++;
		}
		tempNode4 = tempNode4->next;
	}

	return count;
}

int CountScaffolds(void)
{
	MOTIF3* tempNode3;
	int count = 0;
	
	tempNode3 = Motif3List;

	while (tempNode3)
	{
		if (tempNode3->type == 3)
		{
			count++;
		}
		tempNode3 = tempNode3->next;
	}

	return count;
}

int OppositeDirectionOKWithNeutralLinks(MOLECULE* sourceNode, MOLECULE* targetNode)
{
	INTERACTION* tempNode;

	tempNode = InteractionsList;

	int found = 0;

	while (tempNode)
	{
		if (
			(
			(!strcmp(tempNode->target, sourceNode->name))
			&& 
			(!strcmp(tempNode->source, targetNode->name)) 
			)
			
			||
			(
			(!strcmp(tempNode->source, sourceNode->name))
			&& 
			(!strcmp(tempNode->target, targetNode->name)) 
			&&
			((!strcmp(tempNode->effect, "0")))
			)
			)
		{
			found = 1;
			break;
		}
		tempNode = tempNode->next;
	}

	return found;
}

void CTestSVGDlg::OnBnClickedButtonShuffledNetworks()
{
	CDialogShuffledNetworks myDialog;

	if (DirLevel == 0)
	{
		DirLevel = 1;
	}
	else
	{
		chdir("..");	
	}
	mkdir("SNAVI_shuffled_nets");
	chdir("SNAVI_shuffled_nets");

	myDialog.DoModal();
	ShuffleTypeOfNetwork = myDialog.typeOfNetwork;
	ShuffleNumberOfNetworks = myDialog.numberOfNetworks;
	ShuffleIsIsland = myDialog.isIsland;
	ShuffleCccpl = myDialog.cccpl;
	ShuffleMotif34 = myDialog.motif34;
	ShuffleMotif5 = myDialog.motif5;
	if (!CancelShuffle)
	{
		ShutOffAllButtons();
		pThreadShuffleNetwork = AfxBeginThread(ShuffleNetworkThread,
									GetSafeHwnd(), 
									THREAD_PRIORITY_BELOW_NORMAL);
	}
	
}


void CTestSVGDlg::OnBnClickedButtonInteractionMatrix()
{
	SortMoleculeListBasedOnReverseConnectivity();
	MOLECULE *tempm=MoleculesList;
	CString store[1000];
	for (int w=0;w<NumberOfMolecules;w++)
	{
		if (!tempm) break;
		store[w]=tempm->name;
		tempm=tempm->next;
	}
 	CDialogInteractionsMatrix myDialog;
	ofstream ob("testoutbool.txt");
	MOLECULE *mol1;
	MOLECULE *mol2;
	mol1=MoleculesList;
	int i=0,j=0;
	while (mol1)
	{
		mol2=mol1->next;
		j=i;
		while (mol2)
		{
			if (IsConnected(mol1, mol2))
			{
				dispMatrix[i][j]=true;
				dispMatrix[j][i]=true;
			}
			else
			{
				dispMatrix[i][j]=false;
				dispMatrix[j][i]=false;
			}
			mol2=mol2->next;
		j++;	
		}
		mol1=mol1->next;
		i++;
	}
	myDialog.DoModal();
}
bool IsConnected(MOLECULE *mol1, MOLECULE *mol2)
{
	int i;
	if  (mol2->number==1)
			mol2->number=1;
	for (i=0;i<mol1->linksCount;i++)
	{
		if (mol1->linksTo[i]==mol2->number)
			return true;
	}
	return false;
}
void SortMoleculeListBasedOnReverseConnectivity (void)
{
	MOLECULE* tempNode1;
	MOLECULE* tempNode2;
	MOLECULE* newList = NULL;
	int saved;
	int next;

	while (MoleculesList)
	{
		tempNode1 = MoleculesList;
		saved = tempNode1->linksCount;
		tempNode2 = tempNode1;

		tempNode1 = tempNode1->next;

		while (tempNode1)
		{
			next = tempNode1->linksCount;
			if (next > saved)
			{
				saved = next;
				tempNode2 = tempNode1;
			}
			tempNode1 = tempNode1->next;
		}
		MoleculesList = RemoveFromList(tempNode2);
		tempNode2->next = 0;
		newList = AddToNewList(newList, tempNode2);
	}
	MoleculesList = newList;
}
UINT ShuffleNetworkThread(LPVOID pParam)
{
	int old=0;
	bool analyzeNetwork=false;
	int numColumns=0;
	if (ShuffleCccpl) analyzeNetwork=true;
	if (ShuffleMotif34) analyzeNetwork=true;
	if (ShuffleMotif5) analyzeNetwork=true;
	char fileName[1000];
	if (ShuffleTypeOfNetwork==1)
	{
		GenerateMiloStyleShuffledNetworks(ShuffleNumberOfNetworks,ShuffleIsIsland, pParam);
	}
	else if (ShuffleTypeOfNetwork==2)
	{
		SwapLinkEffects(ShuffleNumberOfNetworks, pParam);
	}
	else if (ShuffleTypeOfNetwork==3)
	{
		GenerateErdosRenyiNetworks(ShuffleNumberOfNetworks,ShuffleIsIsland, pParam);
	}
	if (analyzeNetwork)
	{
		old=0;		
		ProgressCount2=0;
		ofstream out;
		out.open("shuffled_networks_analysis.htm");
		out << "<html><body><table>";	
		out << "<tr><td>" << "random network #";
		out << "</td><td>" << "interactions";
		out << "</td><td>" << "nodes";
		out << "</td><td>" << "positive links";
		out << "</td><td>" << "negative links";
		out << "</td><td>" << "neutral links";
		numColumns+=6;
		if (ShuffleCccpl)
		{
			out << "</td><td>" << "CC";
			out << "</td><td>" << "GC"; 
			out << "</td><td>" << "CPL";
			numColumns+=3;
		}
		out << "</td><td>" << "islands"; 
		if (ShuffleMotif34)
		{
			out << "</td><td>" << "FBL3";
			out << "</td><td>" << "FBL4";
			out << "</td><td>" << "PFBL3";
			out << "</td><td>" << "PFBL4";
			out << "</td><td>" << "NFBL3";
			out << "</td><td>" << "NFBL4";
			out << "</td><td>" << "Scaffolds";
			out << "</td><td>" << "Bifans";
			out << "</td><td>" << "FFL3";
			out << "</td><td>" << "FFL4";
			out << "</td><td>" << "PFFL3";
			out << "</td><td>" << "PFFL4";
			out << "</td><td>" << "NFFL3";
			out << "</td><td>" << "NFFL4";
			numColumns+=14;
		}
		if (ShuffleMotif5)
		{
			out << "</td><td>" << "FBL5";	
			out << "</td><td>" << "PFBL5";
			out << "</td><td>" << "NFBL5";
			numColumns+=6;
		}
		out << "</td></tr>" << endl;
		for (int j=1;j<=ShuffleNumberOfNetworks;j++)
		{
			FreeNetwork();
			if (ShuffleTypeOfNetwork==1)
				sprintf(fileName, "random_milo_%d.sig", j);
			else if (ShuffleTypeOfNetwork==2)
				sprintf(fileName, "random_effect_%d.sig", j);
			else if (ShuffleTypeOfNetwork==3)
				sprintf(fileName, "random_er_%d.sig", j);
			LoadNetwork(fileName);
			out << "<tr><td>" << j;
			out << "</td><td>" << NumberOfInteractions;
			out << "</td><td>" << NumberOfMolecules;
			out << "</td><td>" << CountPositives();
			out << "</td><td>" << CountNegatives();
			out << "</td><td>" << CountNeutrals();
			if (ShuffleCccpl)
			{
				out << "</td><td>" << ComputeCC();
				out << "</td><td>" << ComputeGC();
				out << "</td><td>" << ComputeAvgPathLength();
			}
			out << "</td><td>" << CountIslands();
			if (ShuffleMotif34)
			{
				ProgressCount2 = old;
				CountDirectedCycles(3, pParam);
				ProgressCount2 = old;
				CountDirectedCycles(4, pParam);
				ProgressCount2 = old;
				CountScaffoldCycles(pParam);
				ProgressCount2 = old;
				CountBifanCycles(pParam);
				ProgressCount2 = old;
				CountConvergedCycles(3, pParam);
				ProgressCount2 = old;
				CountConvergedCycles(4, pParam);
				CountNumberOfEffects();
				out << "</td><td>" << CountFeedbackLoops(3);
				out << "</td><td>" << CountFeedbackLoops(4);
				out << "</td><td>" << CountPositiveFeedbackLoops(3);
				out << "</td><td>" << CountPositiveFeedbackLoops(4);
				out << "</td><td>" << CountNegativeFeedbackLoops(3);
				out << "</td><td>" << CountNegativeFeedbackLoops(4);
				out << "</td><td>" << CountScaffolds();
				out << "</td><td>" << CountBifans();
				out << "</td><td>" << CountFeedforwardLoops(3);
				out << "</td><td>" << CountFeedforwardLoops(4);
				out << "</td><td>" << CountPositiveFeedforwardLoops(3);
				out << "</td><td>" << CountPositiveFeedforwardLoops(4);
				out << "</td><td>" << CountNegativeFeedforwardLoops(3);
				out << "</td><td>" << CountNegativeFeedforwardLoops(4);
			}
			if (ShuffleMotif5)
			{
				ProgressCount2 = old;
				CountDirectedCycles(5, pParam);
				ProgressCount2 = old;
				out << "</td><td>" << CountFeedbackLoops(5);
				out << "</td><td>" << CountPositiveFeedbackLoops(5);
				out << "</td><td>" << CountNegativeFeedbackLoops(5); 
				out << "</td></tr>" << endl;
			}
			FreeMotifs();
			ProgressCount2+=(NumberOfMolecules/ShuffleNumberOfNetworks);
			old=ProgressCount2;
			sprintf(BasedOnConnectivityMessage, "Analyzed %d random networks out of %d", j, ShuffleNumberOfNetworks);
			//sprintf(BasedOnConnectivityMessage, " %d", ShuffleNumberOfNetworks);
			::PostMessage((HWND) pParam, WM_UPDATE_SHUFFLED_PROGRESS, 0, 0);

		}
		
		out << "</table></body></html>";
		out.close();
	}
	::PostMessage((HWND) pParam, WM_THREAD_SHUFFLED_FINISHED, 0, 0);
	return 0;

}
void GenerateMiloStyleShuffledNetworks(int n, bool island, LPVOID pParam)
{
	INTERACTION* tempNode;
	INTERACTION* tempNode1;
	INTERACTION* tempNode2;
	ofstream out;
	int randomNumber;
	char fileName[100];
	char tempStr[100];
	int i, j;
	double pc2=0.0;
	ProgressCount2=0;
	for (i = 1; i <= n;)
	{
		sprintf(fileName, "random_milo_%d.sig", i);

		out.open(fileName);

		tempNode = InteractionsList;

		tempNode1 = InteractionsList;

		while (tempNode1)
		{
			randomNumber = GetRandomNumber(NumberOfInteractions);

			tempNode2 = InteractionsList;

			for (j = 0; j < randomNumber; j++)
			{
				tempNode2 = tempNode2->next;
			}

			if ((tempNode1 != tempNode2) && (ThereIsNoLinkAlready(tempNode1, tempNode2)))
			{
				
				strcpy(tempStr, tempNode1->target);
				strcpy(tempNode1->target, tempNode2->target);
				strcpy(tempNode2->target, tempStr);

				strcpy(tempStr, tempNode1->targetAccHuman);
				strcpy(tempNode1->targetAccHuman, tempNode2->targetAccHuman);
				strcpy(tempNode2->targetAccHuman, tempStr);

				strcpy(tempStr, tempNode1->targetAccMouse);
				strcpy(tempNode1->targetAccMouse, tempNode2->targetAccMouse);
				strcpy(tempNode2->targetAccMouse, tempStr);

				strcpy(tempStr, tempNode1->targetLocation);
				strcpy(tempNode1->targetLocation, tempNode2->targetLocation);
				strcpy(tempNode2->targetLocation, tempStr);

				strcpy(tempStr, tempNode1->targetType);
				strcpy(tempNode1->targetType, tempNode2->targetType);
				strcpy(tempNode2->targetType, tempStr);
	
			}
			tempNode1 = tempNode1->next;
		}

		tempNode = InteractionsList;
		while (tempNode)
		{
			
			out << tempNode->source << " " << tempNode->sourceAccHuman << " " << tempNode->sourceAccMouse << " " << tempNode->sourceType << " " << tempNode->sourceLocation << " " << tempNode->target << " ";
			out << tempNode->targetAccHuman << " " << tempNode->targetAccMouse << " " << tempNode->targetType << " " << tempNode->targetLocation << " " << tempNode->effect << " " << tempNode->typeOfInteraction;
			out << " " << tempNode->pmid << endl;
			
			tempNode = tempNode->next;
		}

		out.close();

		if (island)
		{
			FreeNetwork();
			LoadNetwork(fileName);
			if (CountIslands()==1)
			{
				i++;
				pc2+=(NumberOfMolecules/n);
			
			}
			FreeNetwork();
			LoadNetwork(OriginalNetworkName);
		}
		else
		{
			i++;
			pc2+=double(NumberOfMolecules/n);
		}
		ProgressCount2=int(pc2);
		sprintf(BasedOnConnectivityMessage, "Created %d random networks out of %d", i, ShuffleNumberOfNetworks);
		//sprintf(BasedOnConnectivityMessage, " %d", ShuffleNumberOfNetworks);
		::PostMessage((HWND) pParam, WM_UPDATE_BASED_ON_CONNECTIVITY_PROGRESS, 0, 0);
		
	}
	ProgressCount2=NumberOfMolecules;
	sprintf(BasedOnConnectivityMessage, "Created %d random networks out of %d", ShuffleNumberOfNetworks, ShuffleNumberOfNetworks);
			//sprintf(BasedOnConnectivityMessage, " %d", ShuffleNumberOfNetworks);
	::PostMessage((HWND) pParam, WM_UPDATE_BASED_ON_CONNECTIVITY_PROGRESS, 0, 0);
}
void SwapLinkEffects(int n, LPVOID pParam)
{
	INTERACTION* tempNode;
	INTERACTION* tempNode1;
	INTERACTION* tempNode2;
	ofstream out;
	int randomNumber;
	char fileName[100];
	char tempStr[100];
	int i, j;
	double pc2=0.0;
	ProgressCount2=0;
	for (i = 1; i <= n;i++)
	{
		sprintf(fileName, "random_effect_%d.sig", i);

		out.open(fileName);
		for (int runs=0;runs<2;runs++)
		{
			tempNode = InteractionsList;

			tempNode1 = InteractionsList;

			while (tempNode1)
			{
				randomNumber = GetRandomNumber(NumberOfInteractions);

				tempNode2 = InteractionsList;

				for (j = 0; j < randomNumber; j++)
				{
					tempNode2 = tempNode2->next;
				}

				if (tempNode1 != tempNode2)
				{
					strcpy(tempStr, tempNode1->effect);
					strcpy(tempNode1->effect, tempNode2->effect);
					strcpy(tempNode2->effect, tempStr);
				}
				tempNode1 = tempNode1->next;
			}
		}
		tempNode = InteractionsList;
		while (tempNode)
		{
			
			out << tempNode->source << " " << tempNode->sourceAccHuman << " " << tempNode->sourceAccMouse << " " << tempNode->sourceType << " " << tempNode->sourceLocation << " " << tempNode->target << " ";
			out << tempNode->targetAccHuman << " " << tempNode->targetAccMouse << " " << tempNode->targetType << " " << tempNode->targetLocation << " " << tempNode->effect << " " << tempNode->typeOfInteraction;
			out << " " << tempNode->pmid << endl;
			
			tempNode = tempNode->next;
		}

		out.close();		
	pc2+=double(NumberOfMolecules/n);
	ProgressCount2=int(pc2);
	sprintf(BasedOnConnectivityMessage, "Created %d random networks out of %d", i, ShuffleNumberOfNetworks);
			//sprintf(BasedOnConnectivityMessage, " %d", ShuffleNumberOfNetworks);
	::PostMessage((HWND) pParam, WM_UPDATE_BASED_ON_CONNECTIVITY_PROGRESS, 0, 0);
	}
	ProgressCount2=NumberOfMolecules;
	i=ShuffleNumberOfNetworks;
	sprintf(BasedOnConnectivityMessage, "Created %d random networks out of %d", i, ShuffleNumberOfNetworks);
			//sprintf(BasedOnConnectivityMessage, " %d", ShuffleNumberOfNetworks);
	::PostMessage((HWND) pParam, WM_UPDATE_BASED_ON_CONNECTIVITY_PROGRESS, 0, 0);
}
void GenerateErdosRenyiNetworks(int n, bool island, LPVOID pParam)
{
	INTERACTION* tempNode;
	MOLECULE* tempNode1;
	MOLECULE* tempNode2;
	INTERACTION* start;
	INTERACTION* tempNode3;
	INTERACTION* tempNode4;
	ofstream out;
	int randomNumber;
	int numPositiveEffects=0;
	int numNegativeEffects=0;
	int numNeutralEffects=0;
	int totalEffects;
	char fileName[100];
	int i, j;
	double pc2=0.0;
	ProgressCount2=0;
	for (i = 1; i <=n;)
	{
		numPositiveEffects=0;
		numNegativeEffects=0;
		numNeutralEffects=0;
		sprintf(fileName, "random_er_%d.sig", i);
		
		out.open(fileName);
		tempNode = InteractionsList;
		tempNode3 = new INTERACTION;

		while (tempNode)
		{
			if (strcmp(tempNode->effect,"+")==0) numPositiveEffects++;
			else if (strcmp(tempNode->effect,"_")==0) numNegativeEffects++;
			else if (strcmp(tempNode->effect,"0")==0) numNeutralEffects++;
			tempNode=tempNode->next;
		}
		totalEffects=numPositiveEffects+numNegativeEffects+numNeutralEffects;
		tempNode=InteractionsList;

		for (int h=0;h<numPositiveEffects;)
		{
			//get random molecule 1

			randomNumber = GetRandomNumber(NumberOfMolecules);

			tempNode1 = MoleculesList;

			for (j = 0; j < randomNumber; j++)
			{
				tempNode1 = tempNode1->next;
			}

			//get random molecule 1

			randomNumber = GetRandomNumber(NumberOfMolecules);

			tempNode2 = MoleculesList;

			for (j = 0; j < randomNumber; j++)
			{
				tempNode2 = tempNode2->next;
			}

			//create interaction

			if (tempNode1 != tempNode2)
			{
				strcpy(tempNode3->source,tempNode1->name);
				strcpy(tempNode3->sourceAccHuman,tempNode1->accHuman);
				strcpy(tempNode3->sourceAccMouse,tempNode1->accMouse);
				strcpy(tempNode3->sourceLocation,tempNode1->location);
				strcpy(tempNode3->sourceType,tempNode1->moleculeType);
				strcpy(tempNode3->target,tempNode2->name);
				strcpy(tempNode3->targetAccHuman,tempNode2->accHuman);
				strcpy(tempNode3->targetAccMouse,tempNode2->accMouse);
				strcpy(tempNode3->targetLocation,tempNode2->location);
				strcpy(tempNode3->targetType,tempNode1->moleculeType);
				strcpy(tempNode3->effect,"+");
				strcpy(tempNode3->typeOfInteraction,"Unknown");
				tempNode3->pmid=0;
                
				if (h==0) start=tempNode3;
				tempNode3->next = new INTERACTION;
				tempNode3=tempNode3->next;
				h++;
			}

		}

		for (int k=0;k<numNegativeEffects;)
		{
			//get random molecule 1

			randomNumber = GetRandomNumber(NumberOfMolecules);

			tempNode1 = MoleculesList;

			for (j = 0; j < randomNumber; j++)
			{
				tempNode1 = tempNode1->next;
			}

			//get random molecule 1

			randomNumber = GetRandomNumber(NumberOfMolecules);

			tempNode2 = MoleculesList;

			for (j = 0; j < randomNumber; j++)
			{
				tempNode2 = tempNode2->next;
			}

			//create interaction

			if (tempNode1 != tempNode2)
			{
				strcpy(tempNode3->source,tempNode1->name);
				strcpy(tempNode3->sourceAccHuman,tempNode1->accHuman);
				strcpy(tempNode3->sourceAccMouse,tempNode1->accMouse);
				strcpy(tempNode3->sourceLocation,tempNode1->location);
				strcpy(tempNode3->sourceType,tempNode1->moleculeType);
				strcpy(tempNode3->target,tempNode2->name);
				strcpy(tempNode3->targetAccHuman,tempNode2->accHuman);
				strcpy(tempNode3->targetAccMouse,tempNode2->accMouse);
				strcpy(tempNode3->targetLocation,tempNode2->location);
				strcpy(tempNode3->targetType,tempNode1->moleculeType);
				strcpy(tempNode3->effect,"_");
				strcpy(tempNode3->typeOfInteraction,"Unknown");
				tempNode3->pmid=0;
                if (numPositiveEffects==0 && k==0) start=tempNode3;
				tempNode3->next = new INTERACTION;
				tempNode3=tempNode3->next;
				k++;
			}
		}

		for (int l=0;l<numNeutralEffects;)
		{
			//get random molecule 1

			randomNumber = GetRandomNumber(NumberOfMolecules);

			tempNode1 = MoleculesList;

			for (j = 0; j < randomNumber; j++)
			{
				tempNode1 = tempNode1->next;
			}

			//get random molecule 1

			randomNumber = GetRandomNumber(NumberOfMolecules);

			tempNode2 = MoleculesList;

			for (j = 0; j < randomNumber; j++)
			{
				tempNode2 = tempNode2->next;
			}

			//create interaction

			if (tempNode1 != tempNode2)
			{
				strcpy(tempNode3->source,tempNode1->name);
				strcpy(tempNode3->sourceAccHuman,tempNode1->accHuman);
				strcpy(tempNode3->sourceAccMouse,tempNode1->accMouse);
				strcpy(tempNode3->sourceLocation,tempNode1->location);
				strcpy(tempNode3->sourceType,tempNode1->moleculeType);
				strcpy(tempNode3->target,tempNode2->name);
				strcpy(tempNode3->targetAccHuman,tempNode2->accHuman);
				strcpy(tempNode3->targetAccMouse,tempNode2->accMouse);
				strcpy(tempNode3->targetLocation,tempNode2->location);
				strcpy(tempNode3->targetType,tempNode1->moleculeType);
				strcpy(tempNode3->effect,"0");
				strcpy(tempNode3->typeOfInteraction,"Unknown");
				tempNode3->pmid=0;
                if (numPositiveEffects==0 && numNegativeEffects ==0 && l==0) start=tempNode3;
				tempNode3->next=new INTERACTION;
				tempNode3=tempNode3->next;
				l++;
			}
		}
		tempNode3=NULL;
		tempNode4 = start;
		for (int te=0;te<totalEffects && (tempNode4);te++)
		{
			
			out << tempNode4->source << " " << tempNode4->sourceAccHuman << " " << tempNode4->sourceAccMouse << " " << tempNode4->sourceType << " " << tempNode4->sourceLocation << " " << tempNode4->target << " ";
			out << tempNode4->targetAccHuman << " " << tempNode4->targetAccMouse << " " << tempNode4->targetType << " " << tempNode4->targetLocation << " " << tempNode4->effect << " " << tempNode4->typeOfInteraction;
			out << " " << tempNode4->pmid << endl;
			
			tempNode4 = tempNode4->next;		
		}
	
		out.close();
		if (island)
		{
			FreeNetwork();
			LoadNetwork(fileName);
			if (CountIslands()==1)
			{
				i++;
				pc2 += (double) (NumberOfMolecules/n);
				ProgressCount2= (int) pc2;
				sprintf(BasedOnConnectivityMessage, "Created %d random networks out of %d", i, ShuffleNumberOfNetworks);
				//sprintf(BasedOnConnectivityMessage, " %d", ShuffleNumberOfNetworks);
				::PostMessage((HWND) pParam, WM_UPDATE_BASED_ON_CONNECTIVITY_PROGRESS, 0, 0);
				}
				FreeNetwork();
				LoadNetwork(OriginalNetworkName);
		}
		else
		{
			i++;
			pc2+=double(NumberOfMolecules/n);
			ProgressCount2=int(pc2);
			sprintf(BasedOnConnectivityMessage, "Created %d random networks out of %d", i, ShuffleNumberOfNetworks);
			//sprintf(BasedOnConnectivityMessage, " %d", ShuffleNumberOfNetworks);
			::PostMessage((HWND) pParam, WM_UPDATE_BASED_ON_CONNECTIVITY_PROGRESS, 0, 0);
		}
		FreeNewInteractionsList(start);

	}
	ProgressCount2=NumberOfMolecules;
	sprintf(BasedOnConnectivityMessage, "Created %d random networks out of %d", ShuffleNumberOfNetworks, ShuffleNumberOfNetworks);
	//sprintf(BasedOnConnectivityMessage, " %d", ShuffleNumberOfNetworks);
	::PostMessage((HWND) pParam, WM_UPDATE_BASED_ON_CONNECTIVITY_PROGRESS, 0, 0);

}
void FreeNewInteractionsList(INTERACTION* start)
{
	INTERACTION* tempNode;

	tempNode = start;

	while ((start!=NULL) && (start->number >= 0) && (start->number <NumberOfMolecules))
	{
		start = tempNode->next;
		free(tempNode);
		tempNode = start;
	}

	NumberOfInteractions = 0;
	return;
}
void CTestSVGDlg::OnBnClickedButtonCreateWebSite2()
{
	CreateStatisticalAnalysisWebPage();
	StartViewer("stats.htm");
	strcpy(LastViewerCall, "stats.htm");
}

void CTestSVGDlg::OnBnClickedButtonGeneList()
{
	ifstream inputFile;
	LPVOID pParam;
	int ret;

	//ret = MessageBox("This function of SNAVI is freely available to non-commercial users. Commercial institutes and industry require a licence agreement and should press cancel and contact us. Please note that when you use this function we record your IP address.",  "Warning!!!", MB_OKCANCEL | MB_ICONEXCLAMATION);

	//if they pressed cancel
	//if (ret == 2)
	//{
	//	return;
	//}

	CFileDialog myDialog(TRUE, NULL, "*.txt", OFN_OVERWRITEPROMPT, NULL, NULL );

	myDialog.DoModal();

	ret = LoadList(myDialog.m_ofn.lpstrFile);

	if (ret == -1)
	{
		return;
	}

	ProgressCount3 = 0;

	CButton* pButtonGeneList = (CButton*) GetDlgItem(IDC_BUTTON_LOAD_NETWORK);
	pButtonGeneList->EnableWindow(0);

	CButton* pButtonLoadNetwork = (CButton*) GetDlgItem(IDC_BUTTON_GENE_LIST);
	pButtonLoadNetwork->EnableWindow(0);

	CButton* pButtonTwoColumns = (CButton*) GetDlgItem(IDC_BUTTON_LOAD_TWO_COLUMN);
	pButtonTwoColumns->EnableWindow(0);


	CDialogIntermediates selectDepth;

	selectDepth.DoModal();

	Depth4Search = selectDepth.m_selection;

	FreeNetwork();

	pThreadProcessList = AfxBeginThread(ProcessListThread,
									GetSafeHwnd(), 
									THREAD_PRIORITY_BELOW_NORMAL);
}


UINT ProcessListThread(LPVOID pParam)
{
	int ret;
	ProgressCount2 = 0;

	if (UseLocalNetworkFlag == 0)
	{
		strcpy(GeneListMessage, "Downloading the reference network... please wait");
		::PostMessage((HWND) pParam, WM_THREAD_PROCESS_LIST_PROGRESS, 0, 0);

		ret = TryToDownloadHumanInteractionsFile(pParam);

		if (ret != 0)
		{
			AfxMessageBox("Failed to download background database!");
			return 0;
		}
	}
	else
	{
		AfxMessageBox("Loading the reference network... please wait");
		LoadNetwork(LocalNetwork);
	}
	//ret = LoadNetwork("c:\\Program Files\\SNAVI\\data\\background.sig");

	ProgressCount2 = 0;
	ProgressCount3 = -1;

	MarkNodes();

	Search4Paths(Depth4Search, pParam);

	FreeNetwork();
	
	FreeMatchList();

	LoadNetwork("c:\\subnetwork_output.sig");
	remove("c:\\subnetwork_output.sig");
	
	::PostMessage((HWND) pParam, WM_THREAD_PROCESS_LIST_FINISHED, 0, 0);

	return 0;
}

void CTestSVGDlg::OnBnClickedButtonGeneListHelp()
{
	CDialogViewer viewerDialog;
	strcpy(viewerDialog.fileName, "http://amp.pharm.mssm.edu/SNAVI/help/load_list.htm");
	viewerDialog.DoModal();
}

int TryToDownloadHumanInteractionsFile(LPVOID pParam)
{
	CString theString;
	LPTSTR strObject = new TCHAR[200];
	CString tempText = "";
	ofstream temp;
	int dwRet;
    int count = 0;
	ofstream debug;
	ofstream out;
	size_t length;
	int num;
	char name1[100];
    char name2[100];
	char acc1[100];
	char acc11[100];
    char acc2[100];
	char acc22[100];
	char rel[100];
	char type1[100];
	char type2[100];
	char loc1[100];
	char loc2[100];
	char typeOfInt[100];
    int i = 0;
	int interactionsCounter = 1;
    int num1, num2;
	int lineNumber = 0;
	int pmid;
	char pmidStr[100];
	int ret = 0;
	char line[3000];
	CString tempStr;
	CString tempStr1;
	int strIndex = 0;
	int wordCount = 0;
	int lineCount = 0;

	CInternetSession session("My Session");
	CHttpConnection* pServer = NULL;
	CHttpFile* pFile = NULL;
	CString strServerName = "amp.pharm.mssm.edu";
	CString tempUrl;
	INTERNET_PORT nPort = 80;
	
	pServer = session.GetHttpConnection(strServerName, nPort);

	try
	{

		//http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=1521331&retmode=mode
		tempUrl.Format("http://amp.pharm.mssm.edu/SNAVI/data/human.txt");
			
		tempUrl.Replace("http://amp.pharm.mssm.edu", "");

		_tcscpy(strObject, tempUrl);
			
		pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject);
			
		pFile->AddRequestHeaders("test");
		
		pFile->SendRequest();
			
		dwRet = HTTP_STATUS_OK;

		if (dwRet == HTTP_STATUS_OK)
		{		
			try 
			{
				int count = 0;
				char* buff;
				int buffIndex = 0;
				//length = pFile->GetLength();
				buff = (char*) malloc(sizeof(char)*10000000);

				while (pFile->ReadString(szBuff, 4096))
				{
					    ProgressCount2++;
						::PostMessage((HWND) pParam, WM_THREAD_PROCESS_LIST_PROGRESS, 0, 0);
						length = strlen(szBuff);
						szBuff[length] = 0;
						
						name1[0] = 0;
						sscanf(szBuff, "%s %s %s %s %s %s %s %s %s %s %s %s %s", name1, acc1, acc11, type1, loc1,
							name2, acc2, acc22, type2, loc2, rel, typeOfInt, pmidStr);
						pmid = atoi(pmidStr);

		num2 = GetNumberBasedOnString(name2);
		MoleculesList = AddToMoleculesWithLink(name1, acc1, acc11, type1, loc1, num2);
		num1 = GetNumberBasedOnString(name1);
		MoleculesList = AddToMoleculesWithLink(name2, acc2, acc22, type2, loc2, num1);
		
		InteractionsList = AddToInteractions(name1, acc1, acc11, loc1, type1, name2, acc2, acc22,
						  loc2, type2, rel, typeOfInt, pmid);
				}
				free(buff);
			}
			catch (CInternetException* pEx)
			{
				return -1;
				//AfxMessageBox("You must be connected to the internet in order to download an update!");
			}
		}

		delete pFile;
	}
	catch (CInternetException* pEx)
	{
		return -1;
		//AfxMessageBox("You must be connected to the internet in order to download an update!");
	}
	if (tempText.Find("The page cannot be found") != -1)
	{
		return -1;
	}
	else
	{
		ProgressCount2 = 0;
		ProgressCount3 = -1;
		return 0;
	}
	
}


int LoadList(char* fileName)
{
	ifstream inputFile;
    char name[100];
    int i = 0;
	int ret = 0;

	inputFile.open(fileName);

	while ((!inputFile.eof()) && (i < 100))
    { 
		name[0] = 0;

		inputFile >> name;
		if (!strcmp(name, ""))
		{
			if (i == 0)
			{
				ret = -1;
			}
			break;
		}
		MatchList = AddToMatchList(name);
	    i++;
    }

	inputFile.close();


    return ret;
}

MOLECULE* AddToMatchList(char* name)
{			
	MOLECULE* tempNode;
	CString tempStr;

	tempStr = name;

	tempStr.MakeUpper();

	
    /* if the list is empty */
    if (!MatchList)
    {
         /* just store this information */
	    MatchList = (MOLECULE*) malloc(sizeof(MOLECULE));
        strcpy(MatchList->name, tempStr.GetBuffer());
		MatchList->next = 0;
		NumberOfMatchMolecules = 1;
	    return MatchList;	
    }
    
    
    /* look for a match or loop all the way to the end */
    tempNode = MatchList;

    /* loop until a match was found or the end */
    while ((tempNode->next != 0) && (strcmp(tempNode->name, tempStr.GetBuffer())))
    {
	    tempNode = tempNode->next;
    }

    /* if a match was found add one to the count */
    if (!strcmp(tempNode->name, tempStr.GetBuffer()))
    {
		return MatchList;
    }
    
    /* just store this information in a new node */
    tempNode->next = (MOLECULE*) malloc(sizeof(MOLECULE));
    tempNode = tempNode->next;
    tempNode->next = 0;
	NumberOfMatchMolecules++;
    strcpy(tempNode->name, tempStr.GetBuffer());

    return MatchList;  
}

void Search4Paths(int depth, LPVOID pParam)
{
	MOLECULE* tempNode1;
	MOLECULE* tempNode2;
	MOLECULE* temp2MatchNode1;
	MOLECULE* temp2MatchNode2;
	ofstream out;
	int listSoFar[20];

	out.open("c:\\subnetwork_output.sig");
	
	temp2MatchNode1 = MatchList; 

	while (temp2MatchNode1)
	{	
		tempNode1 = MoleculesList;

		while (tempNode1)
		{
			if (!strcmp(tempNode1->name, temp2MatchNode1->name))
			{
				strcpy(tempNode1->moleculeList, "YES");
				temp2MatchNode2 = temp2MatchNode1->next; 

				while (temp2MatchNode2)
				{	
					tempNode2 = MoleculesList;

					while (tempNode2)
					{
						if (!strcmp(tempNode2->name, temp2MatchNode2->name))
						{
							sprintf(GeneListMessage, "Searching for paths from %s to %s... please wait", tempNode1->name, tempNode2->name);
							ProgressCount2++;
							::PostMessage((HWND) pParam, WM_THREAD_PROCESS_LIST_PROGRESS, 0, 0);
							strcpy(tempNode2->moleculeList, "YES");
							listSoFar[0] = tempNode1->number;
							ClearInteractionsFlag();
							IndexOfGlobalList = 0;
							CountNumberOfPathwaysToOutputAndDump(out, temp2MatchNode2->name, tempNode1, depth, 1, listSoFar);
							AddInteractionsForFeedbackLoops(out);
						}
						tempNode2 = tempNode2->next;
					}
					temp2MatchNode2 = temp2MatchNode2->next;
				}
			}
			tempNode1 = tempNode1->next;
		}
		temp2MatchNode1 =  temp2MatchNode1->next;
	}
	out.close();
}

void MarkNodes(void)
{
	MOLECULE* temp1;
	MOLECULE* temp2;
	int flag;

	temp1 = MoleculesList;

	while (temp1)
	{
		temp2 = MatchList;
		flag = 0;
		while (temp2)
		{
			if (!strcmp(temp1->name, temp2->name))
			{
				strcpy(temp1->moleculeList, "YES");
				flag = 1;
				break;
			}
			temp2 = temp2->next;
		}
		if (flag == 0)
		{
			strcpy(temp1->moleculeList, "NO");
		}
		temp1 = temp1->next;
	}
	return;
}

void FreeMatchList(void)
{
	MOLECULE* tempNode;

	tempNode = MatchList;

	while (MatchList)
	{
		MatchList = tempNode->next;
		free(tempNode);
		tempNode = MatchList;
	}
	return;
}

void CountNumberOfPathwaysToOutputAndDump(
	ofstream &out, char* targetName, MOLECULE* tempNode, 
	int sizeWeLookFor, int howDeep, int* listSoFar)
{
	MOLECULE* localNode;
	MOLECULE* tempNode3;
	MOLECULE* tempNode4;
	INTERACTION* tempInt;
	int i;

	localNode = tempNode;

	if ((howDeep <= sizeWeLookFor) && 
		(!strcmp(tempNode->name, targetName)))
	{
		AddToGlobalListOfSubNetwork(listSoFar, howDeep);
		for (i = 0; i < howDeep - 1; i++)
		{
				tempNode3 = GetNodeBasedOnNumber(listSoFar[i]);
				tempNode4 = GetNodeBasedOnNumber(listSoFar[i + 1]);
				tempInt = GetInteraction(tempNode3->name, tempNode4->name);
				
				if (!tempInt)
				{
					tempInt = GetInteraction(tempNode4->name, tempNode3->name);
					if (!strcmp(tempNode4->moleculeList, "YES"))
					{
						strcpy(tempInt->sourceList, "YES");
					}
					if (!strcmp(tempNode3->moleculeList, "YES"))
					{
						strcpy(tempInt->targetList, "YES");
					}
				}
				else
				{
					if (!strcmp(tempNode3->moleculeList, "YES"))
					{
						strcpy(tempInt->sourceList, "YES");
					}
					if (!strcmp(tempNode4->moleculeList, "YES"))
					{
						strcpy(tempInt->targetList, "YES");
					}
				}
				if (!tempInt->flag)
				{

					out << tempInt->source << " " << tempInt->sourceAccHuman << " " << tempInt->sourceAccMouse << " " << tempInt->sourceLocation << " " << tempInt->sourceType << " " << tempInt->target << " " << tempInt->targetAccHuman << " " << tempInt->targetAccMouse << " " << tempInt->targetType << " " << tempInt->sourceLocation << " " << tempInt->effect << " " << tempInt->typeOfInteraction << " " << tempInt->pmid << endl;
					tempInt->flag = 1;
				}
				
		}
	}
	else if (howDeep > sizeWeLookFor)
	{
		return;
	}
	else
	{
		for (i = 0; i < tempNode->linksCount; i++)
		{	
			localNode = GetNodeBasedOnNumber(tempNode->linksTo[i]);
			
			if (NotAlreadyInList(listSoFar, howDeep, localNode->number))
			{
				listSoFar[howDeep] = localNode->number;
				CountNumberOfPathwaysToOutputAndDump(out, targetName, localNode, sizeWeLookFor, howDeep + 1, listSoFar);
			}
		}
	}	
}

int sumFact(int n)
{
	int temp = n;
	int sum = n;
	while (temp)
	{
		sum += temp - 1;
		temp--;
	}
	return sum;
}
void CTestSVGDlg::OnBnClickedButtonSif()
{
	INTERACTION* tempNode;
	ofstream out;

	out.open("network4cytoscape.sif");

	tempNode = InteractionsList;

	while (tempNode)
	{
		if (!strcmp(tempNode->targetType, "DNA"))
		{
			out << tempNode->source << " pd " << tempNode->target << endl;
		}
		else if (!strcmp(tempNode->sourceType, "Messenger"))
		{
			out << tempNode->source << " mp " << tempNode->target << endl;
		}
		else if ((!strcmp(tempNode->targetType, "Messenger")) ||
				(!strcmp(tempNode->targetType, "Ion")))
		{
			out << tempNode->source << " pm " << tempNode->target << endl;
		}
		else
		{
			out << tempNode->source << " pp " << tempNode->target << endl;
		}
		tempNode = tempNode->next;
	}

	MessageBox("The Sif file for Cytoscape was created and it was placed in your current working directory!", "SNAVI", MB_OK | MB_ICONINFORMATION);
}

void CTestSVGDlg::OnBnClickedButtonSaveAsHelp()
{
	MessageBox("Allows you to save loaded networks as SIG files...", "SNAVI Help", MB_OK | MB_ICONINFORMATION);
}

void CTestSVGDlg::OnBnClickedButtonTwoColumnHelp()
{
	CDialogViewer viewerDialog;
		
	strcpy(viewerDialog.fileName, "http://amp.pharm.mssm.edu/SNAVI/help/two_columns.htm");
	viewerDialog.DoModal();
}

void CTestSVGDlg::OnBnClickedButtonRandomHelp()
{
	CDialogViewer viewerDialog;
		
	strcpy(viewerDialog.fileName, "http://amp.pharm.mssm.edu/SNAVI/help/shuffled.htm");
	viewerDialog.DoModal();
}

void CTestSVGDlg::OnBnClickedButtonMfinderHelp()
{
	CDialogViewer viewerDialog;
		
	strcpy(viewerDialog.fileName, "http://amp.pharm.mssm.edu/SNAVI/help/motifs.htm");
	viewerDialog.DoModal();
}

void CTestSVGDlg::OnBnClickedButtonMotifsInput()
{
	// TODO: Add your control notification handler code here
}

void CTestSVGDlg::OnBnClickedButtonValidateHelp()
{
	CDialogViewer viewerDialog;
		
	strcpy(viewerDialog.fileName, "http://amp.pharm.mssm.edu/SNAVI/help/validate.htm");
	viewerDialog.DoModal();
}

void CTestSVGDlg::OnBnClickedButtonPsiMi()
{
	
	
}



void CTestSVGDlg::OnBnClickedButtonDumpClusterHelp()
{
	CDialogViewer viewerDialog;
		
	strcpy(viewerDialog.fileName, "http://amp.pharm.mssm.edu/SNAVI/help/big_cluster.htm");
	viewerDialog.DoModal();
}

void CTestSVGDlg::OnBnClickedButtonSifHelp2()
{
	CDialogViewer viewerDialog;
		
	strcpy(viewerDialog.fileName, "http://amp.pharm.mssm.edu/SNAVI/help/stats.htm");
	viewerDialog.DoModal();
}

void CTestSVGDlg::OnBnClickedButtonSifHelp()
{
	CDialogViewer viewerDialog;
		
	strcpy(viewerDialog.fileName, "http://amp.pharm.mssm.edu/SNAVI/help/sif.htm");
	viewerDialog.DoModal();
}

void CTestSVGDlg::OnBnClickedButtonPajekHelp()
{
	CDialogViewer viewerDialog;
		
	strcpy(viewerDialog.fileName, "http://amp.pharm.mssm.edu/SNAVI/help/pajek.htm");
	viewerDialog.DoModal();
}

void CTestSVGDlg::OnBnClickedButtonGraphvizHelp()
{
	CDialogViewer viewerDialog;
		
	strcpy(viewerDialog.fileName, "http://amp.pharm.mssm.edu/SNAVI/help/graphviz.htm");
	viewerDialog.DoModal();
}

void CTestSVGDlg::OnBnClickedButtonPgHelp()
{
	CDialogViewer viewerDialog;
		
	strcpy(viewerDialog.fileName, "http://amp.pharm.mssm.edu/SNAVI/help/pg.htm");
	viewerDialog.DoModal();
}

void CTestSVGDlg::OnBnClickedButtonMatrixHelp()
{
	CDialogViewer viewerDialog;
		
	strcpy(viewerDialog.fileName, "http://amp.pharm.mssm.edu/SNAVI/help/matrix.htm");
	viewerDialog.DoModal();
}

void CTestSVGDlg::OnBnClickedButtonMotifsHelp()
{
	CDialogViewer viewerDialog;
		
	strcpy(viewerDialog.fileName, "http://amp.pharm.mssm.edu/SNAVI/help/display_motifs.htm");
	viewerDialog.DoModal();
}

void CTestSVGDlg::OnBnClickedButtonSubnet1Help()
{
	CDialogViewer viewerDialog;
		
	strcpy(viewerDialog.fileName, "http://amp.pharm.mssm.edu/SNAVI/help/subnetworks.htm");
	viewerDialog.DoModal();
}

void CTestSVGDlg::OnBnClickedButtonSubnets2Help()
{
	CDialogViewer viewerDialog;
		
	strcpy(viewerDialog.fileName, "http://amp.pharm.mssm.edu/SNAVI/help/subnetworks.htm");
	viewerDialog.DoModal();
}

BOOL CTestSVGDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	int ret;
	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	//ret = LoadUserSetting();

	//if (ret == 1)
	//{
	//	OnBnClickedOk();
	//}

	MoleculesList = NULL;
	InteractionsList = NULL;
	Motif3List = NULL;
	Motif4List = NULL;
	ColorsAndShapesList = NULL;
	NumberOfMolecules = 0;
	NumberOfMotif3 = 0;
	NumberOfMotif4 = 0;
	NumberOfInteractions = 0;
	ProgressCount = 1;
	ProgressCount2 = 1;
	DoDownstreamMaps = 0;
	WebSiteFinishedFlag = 0;
	strcpy(LastViewerCall,"Null");

	CButton* pButtonViewer = (CButton*) GetDlgItem(IDC_BUTTON_VIEWER);
	pButtonViewer->EnableWindow(0);

	CButton* pButtonWebSite = (CButton*) GetDlgItem(IDC_BUTTON_CREATE_WEB_SITE);
	pButtonWebSite->EnableWindow(0);

	CButton* myButton;

	myButton = (CButton*) GetDlgItem(IDC_BUTTON_MOTIFS_INPUT);
	myButton->EnableWindow(0);

	myButton = (CButton*) GetDlgItem(IDC_BUTTON_VALIDATE);
	myButton->EnableWindow(0);


	myButton = (CButton*) GetDlgItem(IDC_BUTTON15);
	myButton->EnableWindow(0);

	myButton = (CButton*) GetDlgItem(IDC_BUTTON_NET);
	myButton->EnableWindow(0);

	myButton = (CButton*) GetDlgItem(IDC_BUTTON19);
	myButton->EnableWindow(0);

	myButton = (CButton*) GetDlgItem(IDC_BUTTON_CREATE_AND_DRAW_PATHWAYS);
	myButton->EnableWindow(0);

	myButton = (CButton*) GetDlgItem(IDC_BUTTON_GENERATE_PATHWAY);
	myButton->EnableWindow(0);

	myButton = (CButton*) GetDlgItem(IDC_BUTTON_MOTIFS);
	myButton->EnableWindow(0);

	CProgressCtrl* pProg = (CProgressCtrl*) GetDlgItem(IDC_PROGRESS);
	pProg->SetRange(0, NumberOfMolecules);

	CButton* pButtonSaveAs = (CButton*) GetDlgItem(IDC_BUTTON_SAVE_AS);
	pButtonSaveAs->EnableWindow(0);

	CButton* pButtonBasedOnConnectivity = (CButton*) GetDlgItem(IDC_BUTTON_BASED_ON_CONNECTIVITY);
	pButtonBasedOnConnectivity->EnableWindow(0);

	CButton* pButtonFromSourceNodes = (CButton*) GetDlgItem(IDC_BUTTON_FROM_SOURCE_NODES);
	pButtonFromSourceNodes->EnableWindow(0);

	CButton* pButtonInteractionsMatrix = (CButton*) GetDlgItem(IDC_BUTTON_INTERACTION_MATRIX);
	pButtonInteractionsMatrix->EnableWindow(0);

	CButton* pButtonShuffledNetworks = (CButton*) GetDlgItem(IDC_BUTTON_SHUFFLED_NETWORKS);
	pButtonShuffledNetworks->EnableWindow(0);

	CButton* pButtonComputeStats = (CButton*) GetDlgItem(IDC_BUTTON_CREATE_WEB_SITE2);
	pButtonComputeStats->EnableWindow(0);

	CButton* pButtonSif = (CButton*) GetDlgItem(IDC_BUTTON_SIF);
	pButtonSif->EnableWindow(0);

	Total3Names = 0;
	Total4Names = 0;
	Total5Names = 0;


	int seed;
	seed = clock();
	srand( (unsigned) seed);

	ShuffleTypeOfNetwork = 0;
	ShuffleNumberOfNetworks = 0;
	ShuffleIsIsland = false;
	ShuffleCccpl = false;
	ShuffleMotif34 = false;
	ShuffleMotif5 = false;

	Bitmap.CreateCompatibleBitmap(GetDC(), 500, 500);
	dcMemoryImage.CreateCompatibleDC(GetDC());
	dcMemoryImage.SelectObject(&Bitmap);

	DirLevel = 0;

	//download the sigfile from the net
	//ret = TryToDownloadSigFile();
	ret = TryToDownloadHelpFile();

#ifdef HELP_FILE_AT_BEGINING
	if (ret != -1)
	{
		CDialogViewer viewerDialog;
		
		//TurnOnAllButtons();
		//turn on all buttons
		viewerDialog.buttonsFlag = 1;
		strcpy(viewerDialog.fileName, "http://amp.pharm.mssm.edu/SNAVI/help/getting_started.htm");
		viewerDialog.DoModal();

	}
	else
	{
		MessageBox("Downloading help file attempt failed!");
	}
	//

#endif

	return TRUE;  // return TRUE  unless you set the focus to a control
}
